【发布时间】:2016-10-19 12:05:50
【问题描述】:
我正在使用 python 2 并阅读了几篇关于此错误的帖子,即 (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(folder) 或 os.remove(absolut) 一次删除所有文件,则会出现错误 32。
有没有办法可以循环遍历 todo 中的每个路径并删除它们而不会出现错误 32?
谢谢,
【问题讨论】:
标签: python windows python-2.7 loops shutil