If you're opening a file using the 'with' statement, do you still need to close the file object?

后端 未结 3 1075
春和景丽
春和景丽 2021-02-19 00:45

For opening files, I\'m used to the apparently older syntax:

f = open(\"sub_ranks.txt\",\"r+\")
for line in f:
    ...
f.close()

I\'ve been tol

3条回答
  •  余生分开走
    2021-02-19 01:33

    No.

    Say you want to print the hostname like so:

    with open("/etc/hostname","r") as f: print f.read() 
    

    It will open the file, do its job then close the file.

提交回复
热议问题