上节中的代码没有关闭文件,这样并不好。
一、代码
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL+C."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally, we close it."
target.close()
这段代码的文件操作流程如下:
打开-清空-写入-关闭
文件打开模式见上一节。
文件写入后记得要close()。
二、更多的文件操作函数
close:关闭文件。跟你的编辑器的文件--》保存。。一个意思。
readline:读取文本文件中一行。
truncate:清空文件,请小心使用。
write:将字符串写入文件。
老办法,使用帮助命令查看各个函数:python -m pydoc file
1.close
close(...)
close() -> None or (perhaps) an integer. Close the file.
Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
一个已经被关闭的文件不能用于进一步的I/O操作
2.readline
readline(...)
readline([size]) -> next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
可选参数限定最大返回字节数
3.truncate
truncate(...)
truncate([size]) -> None. Truncate the file to at most size bytes.
Size defaults to the current file position, as returned by tell().
截断size大小的文件,size取决于当前文件的位置,这个位置可用tell()获取。
4.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.
返回值None.注意由于缓冲的作用,在数据保存到磁盘之前需要flush()或者close()
网友评论
Traceback (most recent call last):
File "ex16_sample.py", line 9, in <module>
raw_input("?")