This article covers operations you can do with a file regarding the Operating System: rename and move a file, check if a file exists, delete a file, make a copy of a file.
This a direct extension of a previous post specifically on the basic operations you can do with a file: create, write, read, append and close files. You can read about it in File Handling in Python.
Delete a File
To delete a file, the os
module is also needed.
Use the remove()
method.
import os
os.remove('my_file.txt')
Check if a File exists
Use the os.path.exists()
method to check the existence of a file.
import os
if os.path.exists('my_file.txt'):
os.remove('my_file.txt')
else:
print('There is no such file!')
Copy a File
For this one, I like to use the copyfile()
method from the shutil
module.
from shutil import copyfile
copyfile('my_file.txt','another_file.txt')
There are a few options to copy a file, but copyfile()
is the fastest one.
Rename and Move a File
If you need to move or rename a file you can use the move()
method from the shutil
module.
from shutil import move
move('my_file.txt','another_file.txt')