1. 打開文件的方式
open函數用來打開文件,語法如下:
open (name[,mode[,buffering]])
open('test.txt'.r)
open函數使用一個文件名作為唯一的強制參數,然后返回一個文件對象。模式(mode)和緩沖(buffering)參數都是可選的。
以下介紹open函數的模式和緩沖函數
1.1 文件模式
'r' :讀模式
'w':寫模式
'a':追加模式
'b':二進制模式
'+':讀/寫模式
‘b’模式改變處理文件的方法。用於處理一些其他類型的文件(二進制文件),比如聲音剪輯或者圖像,那么應該在的模式參數中增加‘b’。參數‘rb’可以用來讀取一個二進制文件。
1.2 緩沖
open函數的第3個參數(可選)控制文件的緩沖。如果參數是0(或者False),I/O(輸入輸出流)就是無緩沖的(所有的讀寫操作都針對硬盤);如果是1(或者是true),
I/O就是有緩沖的(意味着python使用內存來代替硬盤,讓程序變得更快,只用使用flush或者close是才會更新硬盤上的數據)。大於1的數字代表緩沖區的大小(單位字節),-1
(或者任何負數)代表使用默認的緩沖區大小。
2.基本的文件方法
打開文件的方法已經介紹了,那么下一步就是用他們做些有用的事。接下來會介紹文件對象(和一些類文件對象,有時候稱為流)的一些基本方法。
2.1 讀和寫
文件(或流)最重要的能力是提供或者接收數據。如果有一名字為f的類文件對象,那么就可以使用f.write方法和f.read方法(以字符串形式)寫入和讀取數據。
每次調用f.write(string)時,所提供的參數string都會被追加到文件中已存在部分的后面
f = open("somefile.txt", "w") f.write('Hello, ') f.write('Python!') f.close() -------- 結果: Hello,Python!
讀文件很簡單,只要記得告訴流要讀多少字符(字節)即可。
如下:
1 f = open("somefile.txt", "r") 2 print(f.read(4)) 3 print(f.read()) 4 f.close() 6 ------------ 7 結果: 8 D:\Python27\python.exe D:/pythonwork/test01/file_1.py 9 hell 10 o, python!
注意:在調用open時可以省略模式說明,因為‘r’是默認的。
**隨機訪問
以上的例子把文件當成流來操作,也就是說只能按照從頭到尾的順序讀數據。實際上在文件中隨意移動讀取文件位置也是可以的,可以使用類文件對象的方法seek和tell來直接訪問感興趣的部分(這種方法稱為隨機訪問)。
seek(offset[,whence]):這個方法把當前位置(進行讀和寫的位置)移動到offest和whence定義的位置。offset類是一個字節(字符)數,表示偏移量。whence默認是0,表示偏移量是從文件開頭開始計算的(偏移量必須是非負的)。whence可能被設置為1(相對於當前位置的移動,此時偏移量offset可以是負的)或者2(相對於文件結尾的移動)
例子如下:
f = open("somefile.txt", "w") f.write('0123456789') f.seek(5) f.write("hello, python!") f.close() f = open("somefile.txt", "r") print(f.read()) ------------------------ 結果: D:\Python27\python.exe D:/pythonwork/test01/file_1.py 01234hello, python!
tell方法返回當前文件的位置如下列所示:
f = open("somefile.txt", "r") print(f.read(3)) print(f.read(2)) print(f.tell()) --------- 結果: D:\Python27\python.exe D:/pythonwork/test01/file_1.py 012 34 5
注意:f.tell方法返回的數字在這種情況下是一個長整數。但不是所有的情況都是這樣的。
2.2 讀寫行
可以使用file.readline讀取單獨的一行。readline方法可以讀取一個文件中的所有行並將其作為列表返回。
writeline方法和readline方法相反:傳給它一個字符串的列表(實際上任何序列或者可迭代的對象都行),它會把所有的字符串寫入文件(或流)。注意,程序不會增加新行,需要自己添加。
注意:在使用其他的符號作為換行符的平台上,用\r(Mac)和\r\n(Windows中)代替\n。
2.3 關閉文件
應該牢記使用close方法關閉文件。
事實上有專門為這種情況設計的語句,即with語句:
with open("somefile.txt") as somefile:
do_something(somefile)
with語句可以打開文件並將其賦值到變量上(somefile),之后就可以將數據寫入語句提中的文件(或執行其他操作)。文件在語句結束后會被自動關閉,即使是由異常引起的結束也是如此。
***上下文管理器
with語句實際上是很通用的結構,允許使用所謂的上下文管理器(context manager)。上下文管理器是一種支持_enter_和_exit_這兩個方法的對象。
_enter_方法不帶參數,它在進入with語句塊時被調用,返回值綁定到在as關鍵字之后的變量。
2.4 使用基本文件方法
1 import pprint 2 3 4 with open("somefile.txt") as somefile: 5 s1 = somefile.read(7) 6 print(s1) 7 s2 = somefile.read(4) 8 print(s2) 9 10 11 with open("somefile.txt") as somefile: 12 s3 = somefile.read() 13 print(s3) 14 15 16 with open("somefile.txt") as somefile: 17 for i in range(3): # 循環三次 18 print('%s: %s'%(str(i), somefile.readline().strip())) 19 20 21 print(pprint.pprint(open("somefile.txt").readlines())) 22 23 24 # 寫文件 25 with open("somefile.txt", "w") as somefile: 26 somefile.write("this\nis no\nhaiku")
結果:
D:\Python27\python.exe D:/pythonwork/test01/flie_2.py
this
is
no
this
is no
haiku
0: this
1: is no
2: haiku
['this\n', 'is no\n', 'haiku']
None
修改文本文件案例
1 with open("somefile.txt", "r+") as somefile: 2 lines = somefile.readlines() 3 lines[1] = "isn't b\n" 4 somefile.writelines(lines)
3.對文件內容進行迭代
3.1 按字節處理
最常見的對文件內容進行迭代的方法是在while循環中使用read方法。如下例子:
1 # 定義一個表達函數 2 def process(string): 3 print("Processing: ", string) 4 5 6 with open("somefile.txt", "r") as somefile: 7 char = somefile.read(1) 8 while char: 9 process(char) 10 char = somefile.read(1)
可以看到,賦值語句char =f.read(1)被重復的使用,代碼重復通常被認為是一件壞事。為了避免這種情況,可以使用while true/break語句。
1 with open("somefile.txt", "r") as somefile: 2 while True: 3 char = somefile.read(1) 4 if not char: 5 break 6 process(char)
3.2 按行操作
在while中使用readline
1 with open("somefile.txt", "r") as somefile: 2 while True: 3 line = somefile.readline().strip() 4 if not line: 5 break 6 process(line)
用readlines迭代行
1 with open("somefile.txt", "r") as somefile: 2 for line in somefile.readlines(): 3 process(line.strip())
3.3 使用fileinput實現懶惰行迭代
1 for line in fileinput.input("somefile.txt"): 2 process(line)
3.4 文件迭代器
對文件進行迭代而不使用變量存儲文件對象
1 for line in open("somefile.txt"): 2 process(line)
可以對文件迭代器執行和普通迭代器相同的操作。如下:
1 with open("somefile2.txt", 'r+') as somefile: 2 somefile.write('First line\n') 3 somefile.write('Second line\n') 4 somefile.write('Third line\n') 5 lines = somefile 6 print(lines) 7 8 # 將文件內容轉換為list 9 lines = list(open("somefile2.txt")) 10 print(lines) 11 12 first, second, third = open("somefile2.txt") 13 print(first) 14 print(second) 15 print(third)
結果:
D:\Python27\python.exe D:/pythonwork/test01/flie_2.py
['First line\n', 'Second line\n', 'Third line\n']
First line
Second line
Third line
在這個例子中,注意下面的幾點很重要。
- 使用print來向文件內寫入內容,這會在提供的字符串后面增加新的行。
- 使用序列來對一個打開的文件進行解包操作,把每行都放入一個單獨的變量中(這么做是很有使用性的,因為一般不知道文件中有多少行,但它演示了文件對象的“迭代性”)
- 在寫文件后關閉文件,是為了確保數據被更新到硬盤中。建議使用with open(filename) as filename:
