os.remove() in windows gives “[Error 32] being used by another process”

前端 未结 1 405
野的像风
野的像风 2021-01-18 11:35

I know this question has been asked before quiet a lot on SO and elsewhere too. I still couldn\'t get it done. And im sorry if my English is bad

Removing file in lin

相关标签:
1条回答
  • 2021-01-18 11:59

    Pythonic way of reading from or writing to a file is by using a with context.

    To read a file:

    with open("/path/to/file") as f:
        contents = f.read()
        #Inside the block, the file is still open
    
    # Outside `with` here, f.close() is automatically called.
    

    To write:

    with open("/path/to/file", "w") as f:
        print>>f, "Goodbye world"
    
    # Outside `with` here, f.close() is automatically called.
    

    Now, if there's no other process reading or writing to the file, and assuming you have all the permission you should be able to close the file. There is a very good chance that there's a resource leak (file handle not being closed), because of which Windows will not allow you to delete a file. Solution is to use with.


    Further, to clarify on few other points:

    • Its the garbage collector that causes the closure of the stream when the object is destroyed. The file is not auto-closed upon complete reading. That wouldn't make sense if the programmer wanted to rewind, would it?
    • os.close(..) internally calls the C-API close(..) that takes an integer file descriptor. Not string as you passed.
    0 讨论(0)
提交回复
热议问题