关闭打开的文件?

2024-04-19 11:56:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我忘了我打开了多少次文件,但我需要关闭它们我添加了txt.close文件和txt_再来一次。结束在我打开至少两次之后

我跟着泽德·A·肖努力学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()

Tags: thenamefromtxtyouclosereadopen
1条回答
网友
1楼 · 发布于 2024-04-19 11:56:53

为了防止出现这种情况,最好始终使用上下文管理器with打开文件,如:

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

这样您就不必担心显式关闭它。你知道吗

优点:

  1. 如果在with内出现异常,Python将负责关闭文件。你知道吗
  2. 无需明确提及close()。你知道吗
  3. 了解打开文件的作用域/用法更具可读性。你知道吗

参考:PEP 343 The "with" Statement。也可以查看Trying to understand python with statement and context managers以了解更多关于它们的信息。你知道吗

相关问题 更多 >