如何删除文件或文件夹?


当前回答

删除文件夹中的所有文件

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

其他回答

对于删除文件:

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

or

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

这两个函数在语义上是相同的。此函数用于删除文件路径。若路径不是文件,而是目录,则引发异常。

删除文件夹:

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

or

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

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

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

os.removedirs(name)

它使用self删除每个空的父目录,直到父目录包含一些内容

例如,如果目录为空,os.removedirs('abc/xyz/pqr')将按“abc/xyz/pqr”、“abc/xy z”和“abc”的顺序删除目录。

有关更多信息,请查看官方文档:os.unlink、os.remove、os.rmdir、shutil.rmtree、os.removedirs

删除文件夹中的所有文件

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

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

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

您可以使用内置的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()

用于删除文件的Python语法

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

or

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

or

用于Python的pathlib库版本>=3.4

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

Path.unlink(missing_ok=False)

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

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

最佳实践

首先,检查文件或文件夹是否存在,然后将其删除。可以通过两种方式实现:

os.path.isfile(“/path/to/file”)使用异常处理。

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:
    # If it fails, inform the user.
    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 it fails, inform 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 the tree; if it fails, throw an error using try...except.
try:
    shutil.rmtree(mydir)
except OSError as e:
    print("Error: %s - %s." % (e.filename, e.strerror))