我正在使用 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?
谢谢,
最佳答案
它发生在这里:
with open(os.path.join(root, documento), 'r') as fin:
所以您打开并锁定了文件,这就是为什么您无法使用以下方法删除此文件夹的原因:
shutil.rmtree(root)
在这个语句中,你必须在with
语句之外做
关于python 2 [错误 32] 进程无法访问该文件,因为它正被另一个进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40130958/