Menu Close

Python File Delete

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.

Remove the File

To remove the file from the server, you should have use Python built-in os module.

Example

#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.

Example:

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...")

Delete Folder

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.

Conclusion

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.

Other Tutorials


Reference:- Click Here

Python File Write
JavaScript Boolean

Related Posts