使用 python 删除文件夹和子文件夹中的 pdf 文件?

Delete pdf files in folders and subfolders with python?

我尝试删除 300 个 pdf 文件。所有的 pdf 文件都是不同的名称,它们都分布在一个大文件夹中,该文件夹分为许多子文件夹和子文件夹。我如何使用 python 来完成(我使用 python 2.7.8)?

使用shutil.rmtree,可以递归删除目录。

import shutil
shutil.rmtree('/path/to/directory/that/contains/pdfs')

如果目录包含其他非 pdf 文件的文件,请改用以下内容(使用 os.walk to traverse the directories recursively, and os.remove/os.unlink 删除 pdf 文件)。

import os

for parent, dirnames, filenames in os.walk('/path/to/the/directory'):
    for fn in filenames:
        if fn.lower().endswith('.pdf'):
            os.remove(os.path.join(parent, fn))

os.chdir 更改目录。只需做一些调整以定位到其他目录

 #!/usr/bin/env python
    import glob
    import os
    directory='/path/folder1/folder2'
    os.chdir(directory)
    files=glob.glob('*.pdf')
    for filename in files:
        os.unlink(filename)

如果您只想删除 pdf 文件,您可以使用 os.walk 函数和 fnmatch.fnmatch 函数。

import os
from fnmatch import fnmatch

for dirpath, dirnames, filenames in os.walk(os.curdir):
    for file in filenames:
        if fnmatch(file, '*.pdf'):
            os.remove(os.path.join(dirpath, file))

假设您要在保留子文件夹树的同时删除文件,您可以使用递归算法:

import os

def recursively_remove_files(f):
    if os.path.isfile(f):
        os.unlink(f)
    elif os.path.isdir(f):
        map(recursively_remove_files, [os.path.join(f,fi) for fi in os.listdir(f)])

recursively_remove_files(my_directory)