Python-';str';对象没有属性';关闭';

Python-';str';对象没有属性';关闭';,python,file-io,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() 我读了

我花了很长时间试图弄明白为什么我写的这几行代码不需要一个结束属性:

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()
我读了一些东西和其他人的帖子,但是他们的剧本比我现在学的要复杂得多,所以我不知道为什么


我正在努力学习Python,非常感谢您的帮助。

file\u content
是一个字符串变量,它包含文件的内容,与文件无关。使用
open(from_file)
打开的文件描述符将自动关闭:文件对象退出作用域后,文件会话将关闭(在这种情况下,紧接着
.read()

执行
file\u content=open(from\u file.read()
)时,将
file\u content
设置为文件的内容(由
read
读取)。无法关闭此字符串。您需要将文件对象与其内容分开保存,例如:

theFile = open(from_file)
file_content = theFile.read()
# do whatever you need to do
theFile.close()
新建_文件
也有类似问题。您应该将
open(to_file)
调用与
write

open(…)
返回对文件对象的引用,调用
read
读取返回字符串对象的文件,调用
write
写入返回
None
,它们都没有
close
属性

>>> help(open)
Help on built-in function open in module __builtin__:

open(...)
    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.

>>> a = open('a', 'w')
>>> help(a.read)
read(...)
    read([size]) -> read at most size bytes, returned as a string.

    If the size argument is negative or omitted, read until EOF is reached.
    Notice that when in non-blocking mode, less data than what was requested
    may be returned, even if no size parameter was given.
>>> help(a.write)
Help on built-in function write:

write(...)
    write(str) -> None.  Write string str to file.

    Note that due to buffering, flush() or close() may be needed before
    the file on disk reflects the data written.
有几种方法可以解决这个问题:

>>> file = open(from_file)
>>> content = file.read()
>>> file.close()
或者使用python>=2.5

>>> with open(from_file) as f:
...     content = f.read()

带有
将确保文件已关闭。

最好不要覆盖变量
文件
。因此,最好使用open(from_file)作为f:…
来表示
,而不是使用open(from_file)作为file:…
。谢谢。我需要养成阅读Python文档的习惯。因为我不知所措,我试图避免它,但我需要开始习惯它。@Re-l没问题
help
太棒了,我希望能有更多的语言内置,而不是在你找到你想要的东西之前,必须挖掘大量的链接。。。它所做的就是获取底层对象的注释,您甚至可以使用它来记录您自己的函数,稍后您自己的…啊哈!非常感谢你。我没有意识到这个表单中字符串和对象之间的区别。谢谢你澄清这一点。你的例子帮助我理解了它。我没有考虑字符串和文件对象之间的区别,这里的区别不是这样的
theFile
是一个文件,而
theFile.read()
是一个没有关闭函数的字符串。@Nasir我想看看我是否理解正确:所以我不需要关闭函数的原因是因为“file\u content”是一个字符串(因为我对它调用了“read”)@Re-l:你“不需要”的原因关闭是指如果没有更多的引用,Python将自动关闭该文件。当您
打开('file').read()
时,您丢弃了对文件本身的引用,只保留了内容,因此Python将看到没有对文件的引用,并将其关闭。然而,这可能不会马上发生。读取完数据后,显式关闭文件更安全。@BrenBarn啊哈!它只是点击。好先生,谢谢你这样解释。我知道现在发生了什么D