In this Python file handling tutorial, you will learn all about how to delete or remove file from the server as well as local machine. In previous python file handling tutorial we have seen how to write existing file to the server.
Headings of Contents
Remove the File
To remove the file from the server, you should have use Python built-in os module.
#import os module import os #remove myfile.txt from the machine os.remove("myfile.txt")
Check if File exist
To avoid getting an error, you might want to check if the file exists before you try to delete it.
check if file exist, then delete it.
import os if os.path.exists("myfile.txt"): os.remove("myfile.txt") else: print("The file does not exist...")
To delete an entire folder, you need to use the os.rmdir() method.
import os os.rmdir("demofolder")
Note:- You can only remove empty folders.
In this guide, you have learned all about Python file delete with the help of examples. os is the Python built-in module that is used to work with file systems in Python.
I hope you don’t have any confusion regarding how to delete existing file from the server as well as local computer.
If you like python file delete article, please share and keep visiting for further Python tutorials.
Reference:- Click Here