To use Python to delete files from Windows, you need an OS module ! Then take a look at how the OS module deletes files!
The specific implementation method is as follows!
Os.remove (PATH)
Delete the file path. If path is a directory , throw a oserror error. If you want to delete a directory, use RmDir ().
Remove () has the same function as unlink ()
In a Windows system, an exception is thrown when you delete a file that is in use. In Unix, the records in the catalog table are deleted, but the storage of the files is still there.
import osmy_file = " d:/text.txt " # file path if Os.path.exists (my_file): # If file exists # to delete files, use the following two methods. os.remove (my_file) # delete # os.unlink (my_file) else : print (" no such file:%s "%my_file )
os.removedirs (path)
Removes the directory recursively. Similar to RmDir (), if a subdirectory is successfully deleted, Removedirs () will delete the parent directory, but the subdirectory is not successfully deleted and an error will be thrown.
For example, Os.removedirs ("Foo/bar/baz") will first delete the Baz directory and then remove Bar and foo, if they are empty, then subdirectories cannot be deleted successfully and will throw OSError exception
os.rmdir (path)
Delete directory path, requires path to be an empty directory, otherwise throws OSError error
Import OS for in Os.walk (top, topdown=False): for in files: os.remove ( Os.path.join (root, name)) for in dirs: Os.rmdir (Os.path.join (root, name) )
Method 2:
The code is as follows:
Import Shutilshutil.rmtree ()
45. How do I delete a file using Python?