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

时间:2012-08-25 02:11:55

标签: 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()

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

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

提前谢谢。

3 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:2)

open(...)返回对文件对象的引用,调用read on读取返回字符串对象的文件,调用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.

Theres有几种方法可以解决这个问题:

>>> file = open(from_file)
>>> content = file.read()
>>> file.close()

或使用python> = 2.5

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

with将确保文件已关闭。

答案 2 :(得分:0)

执行file_content = open(from_file).read()时,将file_content设置为文件内容(由read读取)。你不能关闭这个字符串。您需要将文件对象与其内容分开保存,例如:

theFile = open(from_file)
file_content = theFile.read()
# do whatever you need to do
theFile.close()

您与new_file存在类似问题。您应该将open(to_file)来电与write分开。