关闭打开的文件?

时间:2017-01-12 00:28:11

标签: python file-io

我忘记了多少次打开文件但我需要关闭它们我在打开它至少2次后添加了txt.close和txt_again.close

我跟随Zed A. Shaw学习Python的艰难之路

#imports argv library from system package
from sys import argv
    #sets Variable name/how you will access it
script, filename = argv
    #opens the given file from the terminal
txt = open(filename)
    #prints out the file name that was given in the terminal
print "Here's your file %r:" % filename
    #prints out the text from the given file
print txt.read()
txt.close()
#prefered method
    #you input which file you want to open and read 
print "Type the filename again:"
    #gets the name of the file from the user
file_again = raw_input("> ")
    #opens the file given by the user
txt_again = open(file_again)
    #prints the file given by the user
print txt_again.read()
txt_again.close()

1 个答案:

答案 0 :(得分:4)

为了防止出现这种情况,最好始终使用Context Manager with打开文件,如:

with open(my_file) as f:
    # do something on file object `f`

这样您就不必担心明确地关闭它。

<强>优点:

  1. 如果在with内引发异常,Python将负责关闭该文件。
  2. 无需明确提及close()
  3. 了解打开文件的范围/用法时更具可读性。
  4. 参考:PEP 343 -- The "with" Statement。另请查看Trying to understand python with statement and context managers以了解有关它们的更多信息。