Python delete Linux path file

In using linux, we often need to perform various operations of deleting and copying files

Command to delete folders under linux system:

  • -r is to recurse downwards, no matter how many levels of directories there are, delete them together
  • -f means to delete directly without any prompt
rm -rf /文件路径

Python code to delete files and folders code

To delete a file or folder using python, you need to use the os module, which is equivalent to executing system instructions:

path is the path of 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.remove(path)  

path is the folder path, note that the folder needs time and space to be deleted

os.rmdir(path)  

The function of unlink is to delete a file like remove, but deleting a file in use will report an error.

os.unlink('F:\新建文本文档.txt') 

But to a certain extent we don't need it, we just need to delete violently:

import shutil
path = 'your path '
shutil.rmtree(path)

All folders in the path will be deleted, which is very convenient to use.

Guess you like

Origin blog.csdn.net/weixin_35770067/article/details/131239585