[英]Delete pdf files in folders and subfolders with python?
I try to delete 300 pdf files. 我尝试删除300个pdf文件。 All the pdf files as different names, and they all spread in one big folder that divided to a lot of sub folders and sub sub folders.
所有pdf文件都是不同的名称,它们都分布在一个大文件夹中,该文件夹分为很多子文件夹和子子文件夹。 How can I do it with python (I work with python 2.7.8)?
我怎么能用python(我使用python 2.7.8)?
Using shutil.rmtree
, you can delete directories recursively. 使用
shutil.rmtree
,您可以递归地删除目录。
import shutil
shutil.rmtree('/path/to/directory/that/contains/pdfs')
If the directory contians other files that is not pdf
file, use following instead (which use os.walk
to traverse the directories recursively, and os.remove
/ os.unlink
to remove the pdf file). 如果目录包含非
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))
If all you want is delete just the pdf
file you can use the os.walk
function and fnmatch.fnmatch
function. 如果您只想删除
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
to change directory. os.chdir
更改目录。 just do some tweak to locate to other directory 只是做一些调整,找到其他目录
#!/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)
Assuming you want to delete the files while maintainig the subfolders tree, you could use a recursive algorithm: 假设您想要在维护子文件夹树的同时删除文件,您可以使用递归算法:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.