Python delete files and folders

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Copyright, without permission, is prohibited reprint


chapter


Delete Files

To delete a file, you need to import OS module, use one of the os.remove()function:

Examples

Delete the file "test.txt":

import os
os.remove("test.txt")

Check if the file exists

To avoid errors, you need to check whether a file exists before deleting:

Examples

Delete the file exists before the examination:

import os
if os.path.exists("test.txt"):
  os.remove("test.txt")
else:
  print("文件不存在")

Delete the folder

To delete the entire folder, use the os.rmdir()method:

Examples

Delete the folder "testfolder":

import os
os.rmdir("testfolder")

Note : You can only delete empty folders.

Guess you like

Origin blog.csdn.net/weixin_43031412/article/details/94380478