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…

Working With Files in Python
Photo by LinkedIn Sales Solutions on Unsplash
Join Medium with my referral link - Konstantinos Patronas
Read every story from Konstantinos Patronas (and thousands of other writers on Medium). Your membership fee directly…

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!

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Check out our Community Discord and join our Talent Collective.

Join Medium with my referral link - Konstantinos Patronas
Read every story from Konstantinos Patronas (and thousands of other writers on Medium). Your membership fee directly…