繁体   English   中英

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

[英]How can I delete a file or folder in Python?

如何删除文件或文件夹?


Python 3.4+ pathlib模块中的Path对象也公开了这些实例方法:

删除文件的 Python 语法

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

或者

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

或者

Python 版本 >= 3.4 的pathlib

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink(missing_ok=False)

用于删除文件或符号链接的取消链接方法。

如果 missing_ok 为 false(默认值),则在路径不存在时引发 FileNotFoundError。
如果 missing_ok 为真,FileNotFoundError 异常将被忽略(与 POSIX rm -f 命令的行为相同)。
在 3.8 版更改: 添加了 missing_ok 参数。

最佳实践

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

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))

利用

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

(请参阅有关shutil的完整文档)和/或

os.remove

os.rmdir

(关于os的完整文档。)

这是一个同时使用os.removeshutil.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))

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

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

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

或者rmdir方法删除一个文件夹:

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

如何在 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/username/directory'

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

from shutil import rmtree
rmtree(directory_path)      # remove everything 

我们可以看到整个东西都被删除了:

>>> directory_path.exists()
False

蟒蛇2

如果您使用的是 Python 2,则有一个名为 pathlib2 的 pathlib 模块的反向移植,可以使用 pip 安装:

$ pip install pathlib2

然后您可以将库别名为pathlib

import pathlib2 as pathlib

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

from pathlib2 import Path

如果太多,您可以使用os.removeos.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 - 它只会递归删除空目录,但它可能适合您的用例。

在 Python 中删除文件或文件夹

在 Python 中有多种删除文件的方法,但最好的方法如下:

  1. os.remove()删除一个文件。
  2. os.unlink()删除一个文件。 它是 remove() 方法的 Unix 名称。
  3. shutil.rmtree()删除目录及其所有内容。
  4. pathlib.Path.unlink()删除单个文件 pathlib 模块在 Python 3.4 及更高版本中可用。

os.remove()

示例 1:使用 os.remove() 方法删除文件的基本示例。

import os
os.remove("test_file.txt")
print("File removed successfully")

示例 2:使用 os.path.isfile 检查文件是否存在并使用 os.remove 将其删除

import os
#checking if file exist or not
if(os.path.isfile("test.txt")):
    #os.remove() function to remove the file
    os.remove("test.txt")
    #Printing the confirmation message of deletion
    print("File Deleted successfully")
else:
print("File does not exist")
#Showing the message instead of throwig an error

示例 3:删除具有特定扩展名的所有文件的 Python 程序

import os 
from os import listdir
my_path = 'C:\Python Pool\Test\'
for file_name in listdir(my_path):
    if file_name.endswith('.txt'):
        os.remove(my_path + file_name)

示例 4:删除文件夹内所有文件的 Python 程序

要删除特定目录中的所有文件,您只需使用 * 符号作为模式字符串。 #导入os和glob模块 import os, glob #循环通过文件夹项目所有文件,并一一删除 for file in glob.glob("pythonpool/*"): os.remove(file) print("Deleted " +字符串(文件))

os.unlink()

os.unlink() 是 os.remove() 的别名或另一个名称。 在 Unix 操作系统中,删除也称为取消链接。 注意:所有功能和语法与 os.unlink() 和 os.remove() 相同。 它们都用于删除 Python 文件路径。 两者都是 Python 标准库中 os 模块中执行删除功能的方法。

shutil.rmtree()

示例 1:使用 shutil.rmtree() 删除文件的 Python 程序

import shutil 
import os 
# location 
location = "E:/Projects/PythonPool/"
# directory 
dir = "Test"
# path 
path = os.path.join(location, dir) 
# removing directory 
shutil.rmtree(path) 

示例 2:使用 shutil.rmtree() 删除文件的 Python 程序

import shutil 
import os 
location = "E:/Projects/PythonPool/"
dir = "Test"    
path = os.path.join(location, dir) 
shutil.rmtree(path) 

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

Pathlib 模块提供了与文件交互的不同方式。 Rmdir 是允许您删除空文件夹的路径功能之一。 首先,您需要为目录选择 Path(),然后调用 rmdir() 方法将检查文件夹大小。 如果它是空的,它将删除它。

这是删除空文件夹而不用担心丢失实际数据的好方法。

from pathlib import Path
q = Path('foldername')
q.rmdir()

shutil.rmtree 是异步函数,所以如果你想检查它什么时候完成,你可以使用 while...loop

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')
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)

对于删除文件:

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

或者

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

这两个功能在语义上是相同的。 此函数删除(删除)文件路径。 如果 path 不是文件并且是目录,则会引发异常。

对于删除文件夹:

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

或者

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

为了删除整个目录树,可以使用shutil.rmtree() os.rmdir仅在目录为空且存在时才有效。

对于向父级递归删除文件夹:

os.removedirs(name)

它使用 self 删除每个空的父目录,直到具有某些内容的父目录

前任。 os.removedirs('abc/xyz/pqr') 将按顺序删除目录 'abc/xyz/pqr', 'abc/xyz' 和 'abc' 如果它们是空的。

有关更多信息,请查看官方文档: os.unlinkos.removeos.rmdirshutil.rmtreeos.removedirs

这是我删除目录的功能。 “路径”需要完整的路径名。

import os

def rm_dir(path):
    cwd = os.getcwd()
    if not os.path.exists(os.path.join(cwd, path)):
        return False
    os.chdir(os.path.join(cwd, path))

    for file in os.listdir():
        print("file = " + file)
        os.remove(file)
    print(cwd)
    os.chdir(cwd)
    os.rmdir(os.path.join(cwd, path))

删除文件夹中的所有文件

import os
import glob

files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
    os.remove(file)

删除目录中的所有文件夹

from shutil import rmtree
import os

// os.path.join()  # current working directory.

for dirct in os.listdir(os.path.join('path/to/folder')):
    rmtree(os.path.join('path/to/folder',dirct))

为避免Éric Araujo 的评论强调的TOCTOU问题,您可以捕获异常以调用正确的方法:

def remove_file_or_dir(path: str) -> None:
    """ Remove a file or directory """
    try:
        shutil.rmtree(path)
    except NotADirectoryError:
        os.remove(path)

由于shutil.rmtree()只会删除目录,而os.remove()os.unlink()只会删除文件。

我个人的偏好是使用 pathlib 对象——它提供了一种更 Python 且不易出错的方式来与文件系统交互,尤其是在您开发跨平台代码时。

在这种情况下,您可以使用 pathlib3x - 它提供了最新的(在撰写此答案 Python 3.10.a0 之日)Python 3.6 或更高版本的 Python pathlib 的反向端口,以及一些附加功能,如“copy”、“copy2” ,“复制树”,“rmtree”等...

它还包装shutil.rmtree

$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib

# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)

# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)

你可以在githubPyPi上找到它


免责声明:我是 pathlib3x 库的作者。

主要有 4 种方法可以从文件夹中删除文件

方法一

os.remove()

获取其他 3 种方法的代码

Python中的文件和文件夹删除功能

Function 描述
os.remove('file_path') 删除指定的文件。
os.unlink('file_path') 删除指定的文件。 在 UNIX 环境中很有用。
pathlib.Path("file_path").unlink() 删除上述路径中的文件或符号链接。
os.rmdir('empty_dir_path') 删除空文件夹。
pathlib.Path(empty_dir_path).rmdir() 取消链接并删除空文件夹。
shutil.rmtree('dir_path') 删除目录和其中包含的文件。

如果编写漂亮且可读的代码是您的一杯茶,我建议使用subprocess

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

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

!rm -r my_dir

传统上,您使用shutil

import shutil
shutil.rmtree(my_dir) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM