上節(jié)中的代碼沒有關(guān)閉文件靶壮,這樣并不好腹殿。
一潮梯、代碼
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()
這段代碼的文件操作流程如下:
打開-清空-寫入-關(guān)閉
文件打開模式見上一節(jié)驹沿。
文件寫入后記得要close()客税。
二况褪、更多的文件操作函數(shù)
close:關(guān)閉文件。跟你的編輯器的文件--》保存更耻。测垛。一個意思。
readline:讀取文本文件中一行秧均。
truncate:清空文件食侮,請小心使用。
write:將字符串寫入文件目胡。
老辦法锯七,使用幫助命令查看各個函數(shù):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.
一個已經(jīng)被關(guān)閉的文件不能用于進一步的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.
可選參數(shù)限定最大返回字節(jié)數(shù)
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取決于當(dāng)前文件的位置誉己,這個位置可用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.注意由于緩沖的作用,在數(shù)據(jù)保存到磁盤之前需要flush()或者close()