python open文件被另一个进程打开怎么办_python 2 [错误32]该进程无法访问文件,因为该文件正在被另一个进程使用...

I'm working with python 2 and have read several posts about this error i.e(this post).

However, I'm still getting the error.

What I do is:

I read the files in a directory, if any of the files contains a specific string, I delete the directory.

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

Then I get the error:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process

I have also tried using the absolute path:

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

Then I will get:

C:\paila_candonga\la_Arepa.tex

C:\paila_candonga\sejodio\laOlla.tex

C:\paila_candonga\sejodio\laPaila.tex

If I remove one file at a time, using the same absolute path and os.remove(''), I won't have problems. If I try to delete all files at once using select_poo() and shutil.rmtree(folder) or os.remove(absolut), I will have the Error 32.

Is there a way I can do a loop through each of the paths in todo and remove them without having the error 32?

Thanks,

解决方案

it happens here :

with open(os.path.join(root, documento), 'r') as fin:

So you have your file open and locked, that is why you are not able delete this folder using:

shutil.rmtree(root)

within this statement, you have to do outside of with statement

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值