《笨辦法學Python》筆記14-----讀寫文件

上節中的代碼沒有關閉文件,這樣并不好。

一、代碼

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容