1. 程式人生 > >python_檔案的開啟和關閉

python_檔案的開啟和關閉



檔案物件 = 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行)