Here is a clear, simple, and exam-ready explanation of Renaming and Deleting Files in Python.
⭐ Renaming & Deleting Files in Python
Python provides file management operations such as renaming and deleting files using the os module.
To use these functions:
import os
⭐ 1. Renaming a File
Python uses os.rename(old_name, new_name) to rename a file.
✔ Syntax
os.rename("old_filename", "new_filename")
✔ Example
import os
os.rename("old.txt", "new.txt")
print("File renamed successfully!")
✔ If the file exists → renamed
❌ If the file does not exist → FileNotFoundError
❌ If new name already exists → FileExistsError (on some systems)
⭐ 2. Renaming a File with Path
os.rename("C:/files/data.txt", "C:/files/data_backup.txt")
⭐ 3. Renaming Directories
You can rename folders too:
os.rename("old_folder", "new_folder")
—————————————–
⭐ 4. Deleting a File
To delete a file, Python uses os.remove() or os.unlink().
Both do the same job.
✔ Syntax
os.remove("filename")
or
os.unlink("filename")
✔ Example
import os
os.remove("sample.txt")
print("File deleted successfully!")
✔ Deletes the file if it exists
❌ If file does not exist → FileNotFoundError
⭐ 5. Check if File Exists Before Deleting
Good practice:
import os
if os.path.exists("sample.txt"):
os.remove("sample.txt")
print("File deleted!")
else:
print("File does not exist.")
—————————————–
⭐ 6. Deleting a Folder
Use os.rmdir() to delete empty folders only.
os.rmdir("myfolder")
❌ Throws error if folder is not empty.
⭐ Deleting Non-Empty Folder (Advanced)
Use shutil.rmtree():
import shutil
shutil.rmtree("myfolder")
⚠ This deletes everything inside the folder — use carefully.
—————————————–
⭐ Exception Handling During Delete/Rename
import os
try:
os.remove("abc.txt")
except FileNotFoundError:
print("File does not exist!")
except PermissionError:
print("Permission denied!")
—————————————–
⭐ Exam-Ready Summary
Renaming Files
- Use
os.rename(old, new) - Works for files and folders
- Raises error if file not found
Deleting Files
- Use
os.remove(filename)oros.unlink(filename) - Removes the file permanently
- Check file existence using
os.path.exists() - Use
os.rmdir()for empty folders - Use
shutil.rmtree()for non-empty folders
⭐ Perfect 5–6 Line Exam Answer
Python provides file renaming and deletion operations through the os module. A file can be renamed using os.rename(old_name, new_name) and deleted using os.remove(filename) or os.unlink(filename). Before deleting, os.path.exists() can be used to check file existence. For directories, os.rmdir() deletes empty folders, while shutil.rmtree() removes non-empty folders. These operations help manage files programmatically.
