Working With Files in Python

Working With Files in Python

The os module of Python provides an Operating System abstraction layer when we want to perform file operations, to delete a file in Linux or Windows using Python we use the same module.$ python
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.remove("t1.txt")
>>> os.remove("t1.txt")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 't1.txt'
>>>

Did you notice the exception? this is because the file does not exist, Python throws an exception if the file is not present.

To rename a file we can use the os.rename function, Python will again throw a file not found an error in case the file does not exist:>>> os.rename("t1.txt","t2.txt")
>>> os.rename("t1.txt","t2.txt")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 't1.txt' -> 't2.txt'

There is a way to check if the file exists before doing a file operation, using the os.path.exists function, which returns True if exists False if does not:>>> if os.path.exists("t2.txt"):
... print("exists")
... else:
... print("does not exist")
...
exists
>>> os.path.exists("t2.txt")
True
>>> os.path.exists("t3.txt")
False

I hope you enjoyed this article!

$ ./buy-me-a-coffee ☕ // found this useful? I write these in my spare time