Move, Rename & Delete Files in Python
In this article I will show you 3 useful operations for managing files in Python:
- Moving a file to another directory
- Renaming a file
- Deleting a file

Moving a file to another directory
To move a file from one directory to another we can use the move function from the shutil package.
It takes 2 arguments:
- The filepath including filename of the file that has to be moved
- The filepath that specifies the destination including the filename
As an example we will move the file Order0001.csv from the directory New to the directory Processed.
import shutil
current_path = 'New/Order0001.csv'
destination_path = 'Processed/Order0001.csv'
shutil.move(current_path,destination_path)After running the code, the Order0001.csv file is not in the New directory anymore, but it is in the Processed directory.
The above code was written in a script in a directory that also contains the New and Processed directories, that is why our relative filepaths worked. To learn more about filepaths, you can read this article:
Warning: If there already is a file with the destination filepath, the existing file will be overwritten.
Renaming a file
Suppose we have a file called bunny.jpg located at: 'C:/Users/BE/Documents'. Now we just want to change the name to rabbit.jpg.
To rename a file we can also use the move function from the shutil package. This time however, we keep the path the same and only change the filename.
import shutil
path = 'C:/Users/BE/Documents'
current_name = 'bunny.jpg'
new_name = 'rabbit.jpg'
current_file = path+'/'+current_name
new_file = path+'/'+new_name
shutil.move(current_file,new_file)After running the code, there is no bunny.jpg file anymore, but there is now a rabbit.jpg file containing the same image.
Since we worked with an absolute filepath the location of the Python script does not matter.
Warning: If there already is a file with the new filename, the existing file will be overwritten.
I believe you can also use this method to change the filetype from txt to csv for example. But changing the filetype of an image requires another method. I wrote a short article about it:
Deleting a file
Now we will take a look at how we can delete a file. Our test subject will be python.jpg located at 'C:/Users/BE/Documents'.
To delete a file you can use the remove function from the os package. All you have to do is specify the filepath.
import os
os.remove('C:/Users/BE/Documents/python.jpg')After running the code, the file can no longer be found in the directory.
And again, since we worked with an absolute filepath the location of the Python script does not matter.
Thank you for reading!
You can get full access to all my posts by joining Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium:
You might also like:
