目錄
1.open函數打開文件
2.文件對象讀寫數據和關閉
3.文本文件和二進制文件的區別
4.編碼和解碼
讀寫文本文件時
讀寫二進制文件時
5.文件指針位置
6.文件緩存區與flush()方法
1.open函數打開文件
使用 open 函數創建一個文件對象,read 方法來讀取數據,write 方法來寫數據
語法:fileObject = open(filename, mode)
filename文件路徑
mode取值:
- "r":為了讀打開一個文件
- "w":為了寫打開一個文件,如果文件已經存在則覆蓋
- "a":為了寫打開一個文件,從文件末尾追加寫入
- "rb":為讀取二進制數據打開文件
- "wb":為寫入二進制數據打開文件
- "ab":追加寫入二進制數據
file1 = open("scores.txt", "r")# 在 filename 前加上 r 表示將反斜線\看做普通的字符,使其沒有其他功能
file2 = open(r"c:\pybook\scores.txt", "r") # 如果沒有 r 前綴,使用轉義序列
file3 = open("c:\\pybook\\scores.txt", "r")
2.文件對象讀寫數據和關閉
open函數創建了一個文件對象,這是_io.TextIOWrapper類的一個實例。這個類包含了讀寫數據和文件關閉的方法。
特別說明:
- readline()是讀取當前行中還未讀取的內容,返回字符串。這個行指以換行符\n 結尾之前的內容
- readlines()是讀取剩下所有未讀取的內容,返回列表,列表的每一個元素時每行未讀取的字符串
- print 函數會自動插入換行符\n,而 write 方法需要顯式地添加一個換行符號\n 用來換行寫數據
- close方法必須被調用,特別是寫文件時,忘記close可能導致文件內容無法寫入
def main():outfile = open("Presidents.txt", "w")outfile.write("QingHui\t")outfile.write("ZhangSan\n")outfile.write("XiaoWang\t")outfile.write("DaBing\n")outfile.write("Others")outfile.close()file2 = open("Presidents.txt", "r")string1 = file2.read(10)print(string1) # QingHui Zhstring3 = file2.readline()print(string3) # angSanstring4 = file2.readlines() # ['XiaoWang\tDaBing\n', 'Others']print(string4)file2.close()main()
按行讀取文件全部數據
# 法一
infile = open("Presidents.txt", "r")
all_data = []
line = infile.readline()
while line != '':all_data.append(line)line = infile.readline()
print(all_data)# 法二
infile = open("Presidents.txt", "r")
all_data = []
for line in infile:all_data.append(line)
print(all_data)"""
['QingHui\tZhangSan\n', 'XiaoWang\tDaBing\n', 'Others\n', '\n', '\n']
['QingHui\tZhangSan\n', 'XiaoWang\tDaBing\n', 'Others\n', '\n', '\n']
"""
簡潔讀寫文件
with open(參數) as file, 自動關閉文件
filepath = r"D:\test\1.txt"with open(filepath, "r") as file:for line in file:print(line, end="")print()with open(filepath, "rb") as file:for line in file:line = line.decode("gbk", "ignore")print(line, end="")print()
讀寫數值數據
由于文本文件中的數據都是字符串類型,所以在進行數值數據的讀寫的時候都要進行相應的數據類型轉換。為了正確地讀出文件中的數字,利用” ”或者\n 的空白符來分隔數字。復雜一點的需要使用正則表達式。
from random import randintdef main():outfile = open("Numbers.txt", "w")for i in range(100):outfile.write(str(randint(0, 9)) + " ")outfile.close()infile = open("Numbers.txt", "r")s = infile.read()numbers = [eval(x) for x in s.split()]for number in numbers:print(number, end = " ")infile.close()main()
3.文本文件和二進制文件的區別
【c基礎】文件操作-CSDN博客
參考這篇文章中《2.文本文件與二進制文件的區別》
4.編碼和解碼
讀寫文本文件時
- 編碼就是將文本模式變成二進制模式。在向一個文本文件寫入指定內容時,會將文本內容按指定編碼類型編碼為二進制,然后放在文件中。
- 解碼就是二進制模式變為文本模式。在從一個文本文件讀取內容時,會將讀取到的二進制內容按指定編碼類型解碼為字符串。
打開文件時,如果不指定編碼方式,則默認utf-8,不過也可以使用encoding參數指定編碼方式。
注意寫入文件時用什么編碼方式,讀取時也最好用什么編碼方式,這樣保證內容能正確讀取到,否則會出現UnicodeDecodeError或者亂碼。
w_file = open("data.txt", "w", encoding="gbk")
w_file.write("你好中國")
w_file.close()# 當用不同的編碼方式讀取文件內容時會報錯或者出現亂碼
r_file = open("data.txt", "r", encoding="utf-8")
for line in r_file:print(line)
r_file.close()"""
會報錯:UnicodeDecodeError:
'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte
"""
如何手動查看文本文件的編碼方式
如何手動修改文本文件的編碼方式:文件另存為時設置

讀寫二進制文件時
讀寫二進制文件時,在用open函數創建文件對象,不能使用encoding函數,否則會"ValueError: binary mode doesn't take an encoding argument"。而是在write函數前對需要寫入的字符串內容進行encode,或者在read讀到的內容后進行decode。
# 寫入數據
file = open("data.txt", "wb")
data = "hello 中國" # 字符串內容
file.write(data.encode("utf-8")) # 將字符串內容按utf-8編碼為二進制寫入到文件中
# 這個時候去查看"data.txt"的編碼就可以看到是 utf-8 編碼了
file.close()# 讀取數據
file = open("data.txt", "rb")
txt = file.read().decode("utf-8")
print(type(txt)) # <class 'str'>
print(txt) # hello 中國
file.close()
5.文件指針位置
在創建文件時,文件指針位置在起始位置,在第 0 行的前面。每次讀或寫時,文件指針位置都會前移。
可以使用seek主動調整文件指針位置。
- seek(arg1, arg2) 第一個參數是偏移量,第二個參數表示模式,0 表示開頭,1 為中間,2 為末尾
- file.seek(16, 0) 表示指針從開頭的第 16 個字符起開始
- file.seek(0, 0) 文件指針跳轉到開頭
tell 方法獲取文件指針當前的位置
file = open("data.txt", "w")
file.write("1234567\n")
file.write("89\n")
file.write("xyz\n")
file.close()file = open("data.txt", "r")
print(f"index={file.tell()}\n") # 1for i in range(12):ret = file.read(1)print(f"value=({ret})") # 1print(f"index={file.tell()}\n") # 1file.close()
運行結果
index=0value=(1)
index=1value=(2)
index=2value=(3)
index=3value=(4)
index=4value=(5)
index=5value=(6)
index=6value=(7)
index=18446744073709551624value=(
)
index=9value=(8)
index=10value=(9)
index=18446744073709551628value=(
)
index=13value=(x)
index=14
注意在換行符號"\n"處,文件指針跳動了兩個單位,是因為windows下"\n"會自動變成"\r\n"。
6.文件緩存區與flush()方法
write 是寫入內存的緩沖區,沒有實時寫入
等到 file.close()后再集中處理,或者緩沖區滿了就真正寫入
緩沖區的作用:磁盤是有壽命的,讀取 or 寫入一次壽命就會減少
import timefile = open("data.txt", "w")
file.write("abcdefg")file.flush() # 刷新,實時寫入
# 此時查看data.txt中會有數據"abcdefg",否則會等到file.close() 才有數據
# 有了這個語句就不怕忘記寫 file.close()這個了time.sleep(30)
file.close() # 文件是在文件關閉后才能寫入,很重要
end