我正在使用Python2,并且已经阅读了几篇关于这个错误的文章,即(this post)。然而,我仍然得到了错误。我所做的是:我读取目录中的文件,如果其中任何文件包含特定字符串,我将删除该目录。
def select_poo():
path = os.walk('/paila_candonga/')
texto = 'poo'
extension = '.tex'
for root, dirs, files in path:
for documento in files:
if extension in documento:
with open(os.path.join(root, documento), 'r') as fin:
for lines in fin:
if texto in lines:
shutil.rmtree(root)
else:
continue然后我得到了错误:
WindowsError: [Error 32] The process cannot access the file because it is being used by another process我还尝试使用绝对路径:
def select_poo():
path = os.walk('/paila_candonga/')
texto = 'poo'
extension = '.tex'
for root, dirs, files in path:
for documento in files:
if extension in documento:
with open(os.path.join(root, documento), 'r') as fin:
for lines in fin:
if texto in lines:
route = (os.path.join(root, documento))
files = os.path.basename(route)
folder = os.path.dirname(route)
absolut= os.path.dirname(os.path.abspath(route))
todo = os.path.join(absolut, files)
print todo
else:
continue然后我会得到:
C:\paila_candonga\la_Arepa.tex
C:\paila_candonga\sejodio\laOlla.tex
C:\paila_candonga\sejodio\laPaila.tex如果我使用相同的绝对路径和os.remove('')一次删除一个文件,就不会有问题。如果我尝试使用select_poo()和shutil.rmtree(文件夹)或os.remove(绝对)一次删除所有文件,将出现错误32。
有没有一种方法可以遍历todo中的每个路径,并在不出现错误32的情况下删除它们?
谢谢,
发布于 2016-10-19 20:13:51
它发生在这里:
with open(os.path.join(root, documento), 'r') as fin:因此,您已经打开并锁定了文件,这就是您无法使用以下命令删除此文件夹的原因:
shutil.rmtree(root)在此语句中,您必须在with语句之外执行操作
https://stackoverflow.com/questions/40130958
复制相似问题