文件對象 = open('文件名','使用方式')
rt:讀取一個txt文件
wt: 只寫打開一個txt文件,(如果沒有該文件則新建該文件)會覆蓋原有內容
at:打開一個txt文件,並從文件指針位置追加寫內容(文件指針默認在末尾)
文件操作錯誤屬於:I/O異常
通常的異常:
1 try: 2 f = open('a.txt','wt') 3 except Exception as e: 4 print(e)
#文件的寫操作
# 函數: 文件對象.write(s)其中s是待寫入文件的字符串{文件對象需要時可寫入的對象}
1 try: 2 fobj = open('anc.txt','wt') #wt:可寫入操作方式/at為在原有的文件內容追加寫入 3 fobj.write('\nmore') #寫函數 4 fobj.close() 5 6 except Exception as err: 7 print(err) 8 9 #結果:anc文件保存至當前目錄下,並寫入“[換行]more”
#案例:學生信息儲存
1 name = 'wanzi' 2 gender = '男' 3 age = 23 4 try: 5 f = open('students.txt','wt') 6 while True: 7 #s = Student(i) 8 #if s: 9 f.write("namegenderge") 10 ans = input("continue(Y/y):") 11 if ans != 'Y' and ans != 'y': 12 break 13 i = i+1 14 f.close() 15 16 except Exception as e: 17 print(e)
#讀文件操作 文件對象.read(n) //返回全部字符串或者n字節字符
1 def writeFile(): #寫文件操作 2 f = open('abc.txt','wt') 3 f.write("Hello world\nI am Code_boy\nMirror_") #三行數據(兩個\n) 4 f.close() 5 6 def readFile(): #讀文件操作 7 f = open('abc.txt','rt') 8 sread = f.read() #文件內容讀取 [如果read(n)有值,則讀取n個字符,為空則讀取全部] 9 print(sread) #將讀取的內容打印輸出 10 f.close() 11 12 try: 13 writeFile() #調用寫文件函數,寫入文件 14 readFile() #調用讀文件函數,讀出(打印)文件內容 15 except Exception as e: 16 print(e) 17 18 ''' 19 結果: 20 Hello world 21 I am Code_boy 22 Mirror_ 23 '''
#讀文件操作 文件對象.readline() //返回一行字符串(讀取連續的字符串,遇到\n或文件末尾結束)
1 def writeFile(): 2 f = open('readline.txt','wt') 3 f.write('Hello\nworld') 4 f.close() 5 6 def readlineFile(): 7 f = open('readline.txt','rt') 8 sreadline = f.readline() #讀取readline文件(只讀一行) 9 print(sreadline,'len=',len(sreadline)) 10 sreadline = f.readline() 11 print(sreadline, 'len=', len(sreadline)) 12 sreadline = f.readline() 13 print(sreadline, 'len=', len(sreadline)) 14 15 f.close() 16 try: 17 writeFile() 18 readlineFile() 19 except Exception as e: 20 print(e) 21 22 結果: 23 Hello #readline中的文件內容: Hello\nworld 結合readline的功能,在讀取一行的數據 24 len= 6 # ‘Hello\n’ >>>> 共計6個字節(換行是因為讀取了\n) 25 world len= 5 #如上類說明 26 len= 0 #文件指針已到達末尾,無法繼續讀出數據故 len = 0
# .readline()可以使用循環的方式(判斷是否讀取為空)來讀取全部,一般都是使用讀單行內容
#但是! .readlines(){加了一個‘s'}就可以直接讀取全部數據:
1 def writeFile(): 2 f = open('readline.txt','wt') 3 f.write('Hello\nworld') 4 f.close() 5 6 def readlinesFile(): 7 f = open('readline.txt','rt') 8 sreadlines = f.readlines() #讀取readlines文件(讀全部行)並以list形式返回 9 #因為是以列表格式返回,所以一般情況下會配合循環(for)從readlines()提取每一行循環打印輸出 10 for i in range(len(sreadlines)): #1號:利用for輸出 11 print(sreadlines[i],end='') 12 13 print(sreadlines) #讀全部內容,並且每一行用'\n'(顯示)隔開 #2號:直接輸出 14 f.close() 15 16 try: 17 writeFile() 18 readlinesFile() 19 except Exception as error: 20 print(error) 21 ''' 22 1號結果: 23 Hello 24 world 25 2號結果: 26 ['Hello\n', 'world'] #>>>也就是readlinese()讀取數據的儲存(list)形式 27 '''
#讀取文件中的學生信息
1 f = open('student1.txt','rt') 2 while True: 3 4 name = f.readline().strip('\n')# *.strip()>>用於移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列。 5 if name == '': 6 break 7 gender = f.readline().strip('\n') 8 age = f.readline().strip('\n') 9 f.close() 10 print(name,gender,age)
#文件編碼
#GBK編碼:中文字符包含簡體和繁體字符,每個字符僅能存儲簡體中文字符 漢字占二字節
#*UTF-8編碼:全球通用的編碼(默認使用)漢字占三字節
#文件打開時,可以指定用encoding參數指定編碼例如:
# f = open('x.txt','wt',encoding = 'utf-8')
# 文件編碼直接決定了文件的空間大小
#案例:UTF-8文件編碼
1 def writeFile(): 2 f = open('utf.txt','wt',encoding = 'utf-8') 3 f.write('Hello I am 王宇陽') 4 f.close() 5 6 def readFile(): 7 f = open('utf.txt','rt',encoding='utf-8') 8 sreadlines = f.readlines() 9 for i in sreadlines: 10 print(i) 11 f.close() 12 try: 13 writeFile() 14 readFile() 15 except Exception as error: 16 print(error) 17 18 # 結果: Hello I am 王宇陽
#文件指針(文件結束標志:EOF)...文件對象.tell()[返回一個整數,整數則是指針的位置]
1 f = open('zz.txt','wt',encoding='utf-8') 2 print(f.tell()) #指針位置:0 3 f.write('abcdef 你好') 4 print(f.tell()) #指針位置:13 5 f.close() 6 f = open('zz.txt','rt',encoding='utf-8') 7 f.tell() #文件指針歸零 8 s = f.read(3) 9 print(s,f.tell()) #輸出read讀取內容並返回指針位置。讀取大小和指針位置相符 10 f.close() 11 #結果: 12 0 13 13 14 abc 3
#操作指針...文件對象.seek(offset[,whence])
# offset:開始的偏移量,代表着需要偏移的字節數
# whence:[可選]默認值為‘0’,給offset參數一個定義,表示從那個位置開始偏移,0:文件開頭 1:文件當前位置 2:文件末尾
#----注意,只有 “rt+ wt+ at+” 的打開方式可以調整指針,其他的打開方式不支持指針操作
1 def writeFile(): 2 f = open('zz1.txt','wt+',encoding='utf-8') 3 print(f.tell()) #返回初始指針位置 >>> 0 4 f.write('123') #寫入3字節內容 5 print(f.tell()) #返回當前(寫入文件后的)指針位置 6 f.seek(2,0) #指針從開頭位置偏移2字節即:1 2 . 3(點的位置) 7 print(f.tell()) #返回指針位置>>>2 8 f.write('abc') #從當前指針位置寫入‘abc’(覆蓋了‘3’) 9 print(f.tell()) #返回指針位置>>>5 10 f.close()
1 def readFlie(): 2 f = open('zz1.txt','rt+',encoding='utf-8') 3 r = f.read() 4 print(r) 5 f.close() 6 7 writeFile() 8 readFlie() 9 #結果: 10 0 11 3 12 2 13 5 14 12abc 15 '''
#二進制文件
#打開方式:rb wb ab rb+ wb+ ab+
'''
實踐中總結:
1' list內容寫入文件在需要專成str格式,應為列表格式文件不接受或者采用 (f.a) 的樣式;(案例綜合:教材管理95-101行)