15

我很想弄清楚为什么我写的这几行代码不需要关闭属性:

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,希望能得到任何帮助。

4

3 回答 3

12

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

于 2012-08-25T02:16:10.183 回答
3

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()

with将确保文件已关闭。

于 2012-08-25T02:18:09.327 回答
1

当您这样做时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.

于 2012-08-25T02:17:53.593 回答