如何删除文件或文件夹?


当前回答

如果您喜欢编写一段漂亮且可读的代码,我建议使用子流程:

import subprocess
subprocess.Popen("rm -r my_dir", shell=True)

如果你不是软件工程师,那么可以考虑使用Jupyter;您可以简单地键入bash命令:

!rm -r my_dir

传统上,您使用shutil:

import shutil
shutil.rmtree(my_dir) 

其他回答

os.remove()删除文件。os.rmdir()删除空目录。shutil.rmtree()删除目录及其所有内容。


Python 3.4+pathlib模块中的路径对象还公开了以下实例方法:

pathlib.Path.unlink()删除文件或符号链接。pathlib.Path.rmdir()删除空目录。

如果您喜欢编写一段漂亮且可读的代码,我建议使用子流程:

import subprocess
subprocess.Popen("rm -r my_dir", shell=True)

如果你不是软件工程师,那么可以考虑使用Jupyter;您可以简单地键入bash命令:

!rm -r my_dir

传统上,您使用shutil:

import shutil
shutil.rmtree(my_dir) 

您可以使用内置的pathlib模块(需要Python 3.4+,但PyPI上有旧版本的后端:pathlib、pathlib2)。

要删除文件,可以使用unlink方法:

import pathlib
path = pathlib.Path(name_of_file)
path.unlink()

或使用rmdir方法删除空文件夹:

import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()

下面是一个同时使用os.remove和shutil.rmtree的健壮函数:

def remove(path):
    """ param <path> could either be relative or absolute. """
    if os.path.isfile(path) or os.path.islink(path):
        os.remove(path)  # remove the file
    elif os.path.isdir(path):
        shutil.rmtree(path)  # remove dir and all contains
    else:
        raise ValueError("file {} is not a file or dir.".format(path))

shutil.rmtree是异步函数,所以如果你想检查它何时完成,你可以使用while。。。环

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')