Locked lesson.
About this lesson
How to rename and delete a file with Python.
Exercise files
Download this lesson’s related exercise files.
Renaming and Deleting Files.docx59.3 KB Renaming and Deleting Files - Solution.docx
59.3 KB
Quick reference
Renaming and Deleting Files
In this video we'll learn how to rename and delete files.
When to use
Use this whenever you want to rename or delete a file.
Instructions
To rename a file, use the os module (that we've imported previously.)
os.rename("names.txt", "new_names.txt")
That will rename the file from names.txt to it's new name of new_names.txt
To delete a file, we just remove it:
os.remove("names.txt")
Hints & tips
- Use the os module to rename files
- os.rename("names.txt", "new_names.txt") # change the name of the file to new_names.txt
- os.remove("names.txt") # delete (remove) a file
Lesson notes are only available for subscribers.