Python - 'str'对象没有属性'close'

Re-*_*e-l 13 python file-io

嗨,大家好.我正在努力弄清楚为什么不需要成为我编写的这几行代码的结束属性:

from sys import argv
from os.path import exists

script, from_file, to_file = argv

file_content = open(from_file).read()
new_file = open(to_file, 'w').write(file_content)

new_file.close()

file_content.close()
Run Code Online (Sandbox Code Playgroud)

我读了一些关于这个的事情和其他人的帖子,但他们的脚本比我目前学习的要复杂得多,所以我无法弄清楚为什么.

我正在努力学习Python,并感谢任何帮助.

先感谢您.

小智 12

file_content是一个字符串变量,它包含文件的内容 - 它与文件无关.您打开的文件描述符open(from_file)将自动关闭:文件对象在文件对象退出范围后关闭(在这种情况下,紧接在之后.read()).