Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

python can't remove a file after closing it, "being used by another process"

I am trying to remove a file after reading from it, but getting "WindowsError: [Error 32] The process cannot access the file because it is being used by another process"

file = open(self.filePath)
for line in file:
        #do things
file.close()

os.remove(self.filePath) #throws error

os.rename(self.filePath, self.filePath + "old") #throws same error

any ideas??

thank you!

UPDATE: i just restarted my (windows 7) box, started eclipse, moved os.remove("c:filefile.txt") to the first line of my script, ran and got the same error.

UPDATE 2: i used windows explorer to navigate to the file.. first time I couldn't delete it, it was being used by "System". second attempt the delete worked fine. the file is no longer there. now when I run os.remove("c:filefile.txt") WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'c:filefile.txt' then i look in windows explorer and the file is back, empty. i can delete in explorer, then when i run the script to remove, it throws the error (and creates the empty file). any idea what could be going on here?

UPDATE 3: i am an idiot. i was opening the file in the initialization of an object when i tested by moving the "remove" to top of script, i should have put it at the top, not after creating my objects

sorry for taking your time, i've been working on something all weekend that's due tomorrow and panicked when it wouldn't run

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another possibility is that a virus checker still has the file open at the time you try to delete or rename it. This doesn't happen often but when it does, it's really annoying to track down.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...