How to delete a file or folder in python
Today, I will talk to you about how to delete a file or folder in python. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
Using python to delete a file or folder requires the use of the os module.
Import osos.remove (path) # path is the path to the file. If the path is a folder, an OSError error will be thrown. In this case, you need to use rmdir () to delete os.rmdir (path) # path is the folder path. Note that the folder requires time and space to be deleted. Os.unlink ('F:\ new text document .txt') # unlink has the same function as remove to delete a file. But deleting a file that is in use will report an error. Import ospath = 'FRV / New text document. Txt' # File path if os.path.exists (path): # if a file exists # Delete a file, you can use the following two methods. Os.remove (path) # os.unlink (path) else: print ('no such file:%s'%my_file) # returns that the file does not exist import osos.removedirs (path) # recursively deletes the directory. If the subdirectory is deleted successfully, the parent directory will be deleted successfully. If the subdirectory is not deleted successfully, an exception will be thrown. Import osfor root, dirs, files in os.walk (top, topdown=False): for name in files: os.remove (os.path.join (root, name)) for name in dirs: os.rmdir (os.path.join (root, name))
Another way
Import shutilshutil.rmtree () after reading the above, do you have any further understanding of how to delete a file or folder in python? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.