Python 我真的需要关闭文件吗?如果是,为什么和如何?

Python 我真的需要关闭文件吗?如果是,为什么和如何?,python,Python,代码取自“艰苦学习Python”练习17,但我对其进行了一些调整,因此我提出了以下问题: 当我添加行时: file1.close() file2.close() 在这段代码的末尾。我在终端上得到输出: 从python/test.txt复制到python/sampleout.txt: The input file is 18 bytes long Does the output file exist? True Traceback (most recent call last): Fil

代码取自“艰苦学习Python”练习17,但我对其进行了一些调整,因此我提出了以下问题:



当我添加行时:

file1.close()
file2.close()
在这段代码的末尾。我在终端上得到输出:

从python/test.txt复制到python/sampleout.txt:

The input file is 18 bytes long
Does the output file exist? True
Traceback (most recent call last):
  File "python/myprogram0.py", line 16, in <module>
    file1.close()
AttributeError: 'str' object has no attribute 'close'
输入文件的长度为18字节
输出文件是否存在?真的
回溯(最近一次呼叫最后一次):
文件“python/myprogram0.py”,第16行,在
file1.close()
AttributeError:“str”对象没有属性“close”

没有这两行代码就可以正常工作。但我想我还是会问的


那么我做错了什么?最后一位是什么意思?

您不是在关闭文件,而是试图“关闭”文件名,它是一个字符串。您需要做的是将
open(…)
的返回值保存在变量中,并对其调用
close

infile = open(file1)
indata = infile.read()
infile.close()
在现代代码中,最好使用
with
语句,而不是显式调用
close
;当with语句退出时,无论是因为代码运行到完成,还是因为引发了异常,文件都会自动关闭:

from sys import argv
from os.path import exists

script, input_file_name, output_file_name = argv

print("Copying from {} to {}:".format(input_file_name, output_file_name))

with open(input_file_name) as input_file:
    data = input_file.read()

print("The input file is {} bytes long".format(len(data)))
print("Does the output file exist? {}".format(exists(output_file_name)))

with open(output_file_name, 'w') as output_file:
    output_file.write(data)
您需要这样做:

  indata = open(file1)
  mystring = indata.read()
  indata.close()

在您的情况下,file1和file2是字符串,要关闭文件,请使用文件描述符:

indata.close()
outdata.close()
在这里阅读Python中的文件操作:
通常,一旦tit的filedescriptor超出范围,Python就会隐式关闭文件。请阅读Python的变量范围。

这是因为file1file2变量是字符串而不是文件描述符,请先将文件描述符存储在变量中,然后在使用后关闭它

f1 = open(file1)
# Read the contents of the file
f1.close()
这同样适用于file2变量。您应该使用with语句,因为with块之后文件会自动关闭

with open(file1) as f1:  # The file1 is open
    indata = f1.read()
    with open(file2) as f2:  # The file2 is open
        # The file1 and file2 will be automatically closed after the next line
        f2.write(indata)

当您打开一个文件时,您会得到一个文件描述符,它基本上是内核持有的结构中的一个索引,该结构存储所有打开文件的引用,因此当您完成使用该文件时,您需要关闭它并删除该引用。要处理使用文件描述符访问文件,进程必须通过系统调用将文件描述符传递给内核,内核将代表进程访问文件。

我建议给出
file1
file2
更合适的名称,例如
input\u file\u name
output\u file\u name
。关键字
还将确保在缩进后的代码中遇到错误时关闭文件,而不仅仅是在执行顺利时。更具体地说,它确保对给定的调用
\uuuuuuuuuuuuuuuuuuuuuuuuuu
\uuuuuuuuuuuuuuuuuuuu
都不是文件对象或文件描述符
indata
是一个字符串,
outdata
None
。仍然会得到此错误回溯(最近一次调用):文件“python/myprogram0.py”,第16行,在indata.close(file1)AttributeError中:“str”对象没有属性“close”
with open(file1) as f1:  # The file1 is open
    indata = f1.read()
    with open(file2) as f2:  # The file2 is open
        # The file1 and file2 will be automatically closed after the next line
        f2.write(indata)