What can I do with a closed file object?

后端 未结 1 1285
心在旅途
心在旅途 2021-02-07 05:59

When you open a file, it\'s stored in an open file object which gives you access to various methods on it such as reading or writing.

>>> f = open(\"fil         


        
相关标签:
1条回答
  • 2021-02-07 06:30

    One use is using the name to reopen the file:

    open(f.name).read()
    

    I use the name attribute when changing a file content using a NamedTemporaryFile to write the updated content to then replace the original file with shutil.move:

    with open("foo.txt") as f, NamedTemporaryFile("w", dir=".", delete=False) as temp:
        for line in f:
            if stuff:
                temp.write("stuff")
    
    shutil.move(temp.name, "foo.txt")
    

    Also as commented you can use the f.closed to see if the file is really closed.

    0 讨论(0)
提交回复
热议问题