我想删除300个PDF文件。这些文件都有不同的名称,它们散布在一个大文件夹中,该文件夹被分成多个子文件夹和子子文件夹。我可以如何使用Python进行操作(我正在使用Python 2.7.8)?
我想删除300个PDF文件。这些文件都有不同的名称,它们散布在一个大文件夹中,该文件夹被分成多个子文件夹和子子文件夹。我可以如何使用Python进行操作(我正在使用Python 2.7.8)?
shutil.rmtree
,您可以递归删除目录。import shutil
shutil.rmtree('/path/to/directory/that/contains/pdfs')
如果目录中包含其他不是 pdf
文件的文件,请改用以下方法(该方法使用os.walk
递归遍历目录,并使用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))
如果你只想删除 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))
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)
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)