5.1 讀寫文本數據
讀取文本內容:open()函數配合rt模式,例如:
>>> with open("myfile.txt", "rt") as f:
... data = f.read()
... print (data)
...
line 1 ---
line 2 ---
line 3 ---
文本寫入:open()函數配合wt模式,如果待操作的文件已存在,會清除並覆蓋原先的內容,例如:
>>> with open("myfile.txt", "wt") as f:
... f.write("new line 1 ---\n")
... f.write("new line 2 ---\n")
... f.write("new line 3 ---\n")
已存在的文件結尾處追加內容: open()函數的at模式,例如:
>>> with open("myfile.txt", "at") as f:
... f.write("new line 4 ---\n")
注:文件的讀寫默認是系統編碼,(系統編碼查詢:sys.getdefaultencoding()),一般都是utf-8,也可以自己選擇編碼參數
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> with open("myfile.txt", "at", encoding="latin-1") as f:
... f.write("new line 5 ---\n")
python能識別出幾百種可能的文本編碼,常見的有ascii, latin-1,utf-8以及utf-16。 在web應用中使用utf-8通常比較保險。
with語句:會爲使用的文件創建一個上下文環境,當程序離開with語句塊後,文件將自動關閉,我們並不一定要使用with語句,不使用with時候,需要手動關閉文件。例如:
>>> f = open("myfile.txt", "rt")
>>> data = f.read()
>>> f.close()
>>> print (data)
new line 1 ---
new line 2 ---
new line 3 ---
new line 4 ---
new line 5 ---
注意:換行符在unix和windows上不同(即\n和\r\n)。默認python工作在“通用型換行符”模式下,該模式中,常見的換行符格式都能識別出來,在讀取時會將換行符轉換成\n字符。在輸出時換行符會被轉換成當前系統默認的換行符。如果不想要這種“翻譯”,可以給open()函數提供一個newline=""參數。例如:
>>> with open("myfile.txt", "rt", newline="") as f:
...
例如:window的機器上寫好的hello.txt中原始數據:hello world!\r\n
>>> f = open("hello.txt", "rt")
>>> f.read()
'hello world!\n'
>>> f = open("hello.txt", "rt", newline="")
>>> f.read()
'hello world!\r\n'
讀寫文本文件中遇到編碼錯誤,解決方式:
使用encoding設定編碼(通常使用utf-8),如果還有可能出現錯誤,用可選的errors來處理錯誤。例如:
錯誤被替換成字符
>>> f = open("hello.txt", "rt", encoding="ascii",errors="replace")
錯誤字符過濾掉不讀
>>> f = open("hello.txt", "rt", encoding="ascii",errors="ignore")
5.2 輸出重定向到文件中
想將print()函數輸出重定向到一個文件中,只需要加上file關鍵字即可。例如:
>>> with open("log.txt", "wt") as f:
... print("hello world!!!", file=f)
5.3 以不同的分隔符或結尾符完成打印
在print()中使用sep和end關鍵詞可以修改輸出。例如:
>>> print("A", 1, 2)
A 1 2
>>> print("A", 1, 2, sep=",")
A,1,2
>>> print("A", 1, 2, sep=",", end="!\n")
A,1,2!
輸出中禁止打印換行符
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
>>> for i in range(5):
... print(i, end=" ")
...
0 1 2 3 4 >>>
str.join()可以轉行相同的分隔效果,但是必須轉換成字符串才行,使用沒有print方便。例如:
>>> row = ("A", 1, 2)
>>> print(",".join(row))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 1: expected str instance, int found
>>> print(",".join(str(x) for x in row))
A,1,2
其實不必費那麼大週摺,print()函數就可以辦到
>>> print(*row, sep=",")
A,1,2
>>> print(row, sep=",")
('A', 1, 2)
5.4 讀寫二進制數據
比如圖像、聲音文件等。