首页 文章

删除文件或文件夹

提问于
浏览
1563

如何在Python中删除文件或文件夹?

10 回答

  • 2

    为你们创造一个功能 .

    def remove(path):
        """ param <path> could either be relative or absolute. """
        if os.path.isfile(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))
    
  • 25

    shutil.rmtree是异步函数,因此如果要检查它何时完成,可以使用while循环

    import os
    import shutil
    
    shutil.rmtree(path)
    
    while os.path.exists(path):
      pass
    
    print('done')
    
  • 139

    如何在Python中删除文件或文件夹?

    对于Python 3,要分别删除文件和目录,请分别使用unlinkrmdir Path 对象方法:

    from pathlib import Path
    dir_path = Path.home() / 'directory' 
    file_path = dir_path / 'file'
    
    file_path.unlink() # remove file
    
    dir_path.rmdir()   # remove directory
    

    请注意,您还可以将相对路径与 Path 对象一起使用,并且可以使用 Path.cwd 检查当前工作目录 .

    要删除Python 2中的单个文件和目录,请参阅下面标记的部分 .

    要删除包含内容的目录,请使用shutil.rmtree,并注意这在Python 2和3中可用:

    from shutil import rmtree
    
    rmtree(dir_path)
    

    示范

    Python 3.4中的新功能是 Path 对象 .

    让我们用一个来创建一个目录和文件来演示用法 . 请注意,我们使用 / 来连接路径的各个部分,这可以解决操作系统之间的问题以及在Windows上使用反斜杠的问题(在这里您需要加倍反斜杠,如 \\ 或使用原始字符串,如 r"foo\bar" ) :

    from pathlib import Path
    
    # .home() is new in 3.5, otherwise use os.path.expanduser('~')
    directory_path = Path.home() / 'directory'
    directory_path.mkdir()
    
    file_path = directory_path / 'file'
    file_path.touch()
    

    现在:

    >>> file_path.is_file()
    True
    

    现在让我们删除它们 . 首先是文件:

    >>> file_path.unlink()     # remove file
    >>> file_path.is_file()
    False
    >>> file_path.exists()
    False
    

    我们可以使用globbing删除多个文件 - 首先让我们为此创建一些文件:

    >>> (directory_path / 'foo.my').touch()
    >>> (directory_path / 'bar.my').touch()
    

    然后迭代遍历glob模式:

    >>> for each_file_path in directory_path.glob('*.my'):
    ...     print(f'removing {each_file_path}')
    ...     each_file_path.unlink()
    ... 
    removing ~/directory/foo.my
    removing ~/directory/bar.my
    

    现在,演示删除目录:

    >>> directory_path.rmdir() # remove directory
    >>> directory_path.is_dir()
    False
    >>> directory_path.exists()
    False
    

    如果我们要删除目录及其中的所有内容,该怎么办?对于此用例,请使用 shutil.rmtree

    让我们重新创建我们的目录和文件:

    file_path.parent.mkdir()
    file_path.touch()
    

    并注意 rmdir 失败,除非它是空的,这就是rmtree如此方便的原因:

    >>> directory_path.rmdir()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
        self._accessor.rmdir(self)
      File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
        return strfunc(str(pathobj), *args)
    OSError: [Errno 39] Directory not empty: '/home/excelsiora/directory'
    

    现在,导入rmtree并将目录传递给funtion:

    from shutil import rmtree
    rmtree(directory_path)      # remove everything
    

    我们可以看到整个事情已被删除:

    >>> directory_path.exists()
    False
    

    Python 2

    如果你're on Python 2, there'是backport of the pathlib module called pathlib2,可以用pip安装:

    $ pip install pathlib2
    

    然后你可以将库别名为 pathlib

    import pathlib2 as pathlib
    

    或者直接导入 Path 对象(如此处所示):

    from pathlib2 import Path
    

    如果这太多了,你可以用os.remove or os.unlink删除文件

    from os import unlink, remove
    from os.path import join, expanduser
    
    remove(join(expanduser('~'), 'directory/file'))
    

    要么

    unlink(join(expanduser('~'), 'directory/file'))
    

    你可以用os.rmdir删除目录:

    from os import rmdir
    
    rmdir(join(expanduser('~'), 'directory'))
    

    请注意,还有一个os.removedirs - 它只是递归地删除空目录,但它可能适合您的用例 .

  • 22

    os.remove()删除文件 .

    os.rmdir()删除一个空目录 .

    shutil.rmtree()删除目录及其所有内容 .

    pathlib.Path.unlink()删除文件或符号链接 .

    pathlib.Path.rmdir()删除空目录 .

  • 8

    我建议使用 subprocess ,如果写下一个漂亮可读的代码就是你的一杯茶:

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

    如果您不是软件工程师,那么可以考虑使用Jupyter;你只需输入bash命令:

    !rm -r my_dir
    

    传统上,您使用 shutil

    import shutil
    shutil.rmtree(my_dir)
    
  • 63
    import os
    
    folder = '/Path/to/yourDir/'
    fileList = os.listdir(folder)
    
    for f in fileList:
        filePath = folder + '/'+f
    
        if os.path.isfile(filePath):
            os.remove(filePath)
    
        elif os.path.isdir(filePath):
            newFileList = os.listdir(filePath)
            for f1 in newFileList:
                insideFilePath = filePath + '/' + f1
    
                if os.path.isfile(insideFilePath):
                    os.remove(insideFilePath)
    
  • 3

    使用

    shutil.rmtree(path[, ignore_errors[, onerror]])
    

    (参见shutil的完整文档)和/或

    os.remove
    

    os.rmdir
    

    (关于os的完整文档 . )

  • 2503

    用于删除文件:

    您可以使用unlinkremove .

    os.unlink(path, *, dir_fd=None)
    

    要么

    os.remove(path, *, dir_fd=None)
    

    此函数删除(删除)文件路径 . 如果path是目录,则引发OSError .

    在Python 2中,如果路径不存在,则会引发带有[Errno 2]( ENOENT )的 OSError . 在Python 3中,引发了[Errno 2]( ENOENT )的 FileNotFoundError . 在Python 3中,因为 FileNotFoundErrorOSError 的子类,所以捕获后者会捕获前者 .

    删除文件夹:

    os.rmdir(path, *, dir_fd=None)
    

    rmdir删除(删除)目录路径 . 仅在目录为空时才起作用,否则引发OSError . 为了删除整个目录树,可以使用shutil.rmtree() .

    shutil.rmtree(path, ignore_errors=False, onerror=None)
    

    shutil.rmtree 删除整个目录树 . 路径必须指向目录(但不是指向目录的符号链接) .

    如果ignore_errors为true,则将忽略由删除失败导致的错误,如果为false或省略,则通过调用onerror指定的处理程序来处理此类错误,或者,如果省略,则会引发异常 .

    也可以看看:

    os.removedirs(name)
    

    os.removedirs(name)递归删除目录 . 像rmdir()一样工作,除了如果成功删除了叶子目录,removeirs()尝试连续删除路径中提到的每个父目录,直到引发错误(被忽略,因为它通常意味着父目录不为空) .

    例如,os.removedirs('foo / bar / baz')将首先删除目录'foo / bar / baz',然后删除'foo / bar'和'foo'(如果它们为空) .

  • 1

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

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

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

    rmdir方法删除 empty 文件夹:

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

    用于删除文件的Python语法

    import os
    os.remove("/tmp/<file_name>.txt")
    

    要么

    import os
    os.unlink("/tmp/<file_name>.txt")
    

    最佳实践

    • 首先,检查文件或文件夹是否存在,然后才删除那个文件 . 这可以通过两种方式实现:
      一个 . os.path.isfile("/path/to/file")
      湾使用 exception handling.

    EXAMPLE for os.path.isfile

    #!/usr/bin/python
    import os
    myfile="/tmp/foo.txt"
    
    ## If file exists, delete it ##
    if os.path.isfile(myfile):
        os.remove(myfile)
    else:    ## Show an error ##
        print("Error: %s file not found" % myfile)
    

    异常处理

    #!/usr/bin/python
    import os
    
    ## Get input ##
    myfile= raw_input("Enter file name to delete: ")
    
    ## Try to delete the file ##
    try:
        os.remove(myfile)
    except OSError as e:  ## if failed, report it back to the user ##
        print ("Error: %s - %s." % (e.filename, e.strerror))
    

    相应的输出

    Enter file name to delete : demo.txt
    Error: demo.txt - No such file or directory.
    
    Enter file name to delete : rrr.txt
    Error: rrr.txt - Operation not permitted.
    
    Enter file name to delete : foo.txt
    

    用于删除文件夹的Python语法

    shutil.rmtree()
    

    shutil.rmtree() 的示例

    #!/usr/bin/python
    import os
    import sys
    import shutil
    
    # Get directory name
    mydir= raw_input("Enter directory name: ")
    
    ## Try to remove tree; if failed show an error using try...except on screen
    try:
        shutil.rmtree(mydir)
    except OSError as e:
        print ("Error: %s - %s." % (e.filename, e.strerror))
    

相关问题