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
将确保文件已关闭。