"""讀文件""" # open()函數打開一個文件對象,傳入文件名(路徑)和標示符(讀,寫等操作) # 'r' 標示符標示 '讀' # read()方法一次讀取文件的全部內容,用一個str表示 # 最后調用close()方法關閉文件,且必須有close()方法 >>> file = "/tmp/pt.txt" >>> f = open(file,'r') >>> f.read() '123\n' >>> f.close() # 當文件讀寫產生Error后,后面的f.close()就不會被調用,所以要保證無論是否Error都能正確地關閉文件 # 使用with語句自動調用close()方法 [root@www PythonTest]# cat fileread.py #!/usr/bin/python3.6 # -*- coding utf-8 -*- file = "/tmp/pt.txt" with open(file,'r') as f: print(f.read()) # 調用read()會一次性讀取文件全部內容,這顯然是不實際的,假如文件很大,內存就崩潰了 # read(size)方法每次最多讀取size個字節內容。如不能確定文件大小,反復調用read(size)比較合適 # readline()方法每次讀取一行內容。 # readlines()方法一次讀取所有內容並按行返回list。如果是配置文件,調用readlines()最方便 [root@www PythonTest]# vim fileread.py #!/usr/bin/python3.6 # -*- coding utf-8 -*- file = "/tmp/pt.txt" f = open(file,'r') for line in f.readlines(): print(line.strip()) #strip()去除換行符\n f.close() # 讀取二進制文件,例如圖片,視頻等,使用'rb'模式打開文件 >>> file = "/tmp/test.png" >>> f = open(file,'rb') >>> f.read()>>> file = "/tmp/test.png" # 當讀取非utf-8編碼的文本文件,需要給open()函數傳入encoding參數 >>> f = open(file,'r',encoding='gbk') # 當遇到編碼不規范的文件,可以給open()函數傳入errors參數,表示錯誤后如何處理 >>> f = open(file,'r',encoding='gbk',errors='ignore') #表示遇到錯誤忽略 """寫文件""" # 寫文件和讀文件是一樣的,唯一區別是調用open()函數時,傳入標識符'w'或者'wb'表示寫文本文件或寫二進制文件 # write()方法寫入文件 # 最后調用close()方法關閉文件,且必須有close()方法 # 在'w' 模式寫入文件時,假如文件存在,會默認使用覆蓋的方式 # 如果想使用追加方式使用'a'或'a+'參數.他們都是從文件末尾追加 [root@www PythonTest]# vim filewrite.py #!/usr/bin/python3.6 # -*- coding utf-8 -*- file = "/tmp/pt.txt" f = open(file,'w') #追加使用f = open(file,'a') f.write("hello,word\n") f.close() """讀寫總結""" open()函數參數 open(filename,mode,bufsize,encoding,errors,newline,closefd) filename #要打開的文件夾名.例如/tmp/pt.txt mode #文件打開的模式,詳見下方操作模式列表 bufsize #緩沖區大小.為0時表示打開文件不用緩沖,為1時表示進行緩沖 encoding #文件編碼類型.例如encoding='gbk' errors #錯誤處理方式.例如errors='ignore' newline #控制通用換行符模式的行為,不同的os之間的換行符也不一致 closefd()#控制在關閉文件時是否徹底關閉文件 文件操作符(打開模式),操作符可以組合使用 r #只讀(默認) w #可寫 a #追加數據 b #二進制數據模式,如圖片,視頻等 x #新建一個文件並且可寫,例如open(file,'x'),在直接使用write()函數寫即可 + #打開文件直接更新 t #文本模式(默認) 文件操作 read() #讀 readline() #讀行 readlines() #將整個文件按行讀入到列表中 write() #寫 writelines()#向文件中寫入一個行數據列表 close() #關閉文件,open()了一個文件就必須close一個文件 使用while語句循環讀取文件中的行 #!/usr/bin/python3.6 # -*- coding utf-8 -*- file = '/tmp/pt.txt' f = open(file,'r') while True: line = f.readline() if not line: break print(line) f.close() 使用for循環迭代文件中的所有行 for line in f: pass 處理文件中數據示例: [root@localhost pythontest]# cat /tmp/pts.txt 1 2 3 [root@localhost pythontest]# cat exampletest.py #!/usr/bin/python3.6 # -*- coding utf-8 -*- def file_hd1(name='/tmp/pts.txt'): #定義一個文件處理函數 f = open(name) #打開文件 res = 0 #累加器變量res i = 0 #行數變量i for line in f: #迭代文件中的行 i += 1 print('第%s行的數據為:' % line.strip(),line) res += int(line) #累加每行的數據 print('這些數的和為:',res) #打印數據和 f.close() #關閉文件 if __name__ == '__main__': file_hd1() #調用函數 [root@localhost pythontest]# python3.6 exampletest.py 第1行的數據為: 1 第2行的數據為: 2 第3行的數據為: 3 這些數的和為: 6 """StringIO""" # 有時候,數據讀寫不一定是文件,也可以在內存中讀寫 # "StringIO"的意思就是在內存中讀寫str # StringIO操作的只能是str >>> from io import StringIO >>> f = StringIO() >>> f.write('hello') 5 >>> f.write(' ') 1 >>> f.write(' 1') 2 >>> print(f.getvalue()) hello 1 # 通過str初始化StringIO,實現以行為單位讀取 [root@www PythonTest]# cat fileIO.py #!/usr/bin/python3.6 # -*- coding utf-8 -*- from io import StringIO f = StringIO('hello!\nhi!\nbyebye!') while True: s = f.readline() if s == '': break print(s.strip()) #輸出結果 [root@www PythonTest]# python3.6 fileIO.py hello! hi! byebye! """BytesIO""" # 要操作二進制數據,就需要使用BytesIO # 寫入的不是字符串,而是經過utf-8編碼的bytes >>> from io import BytesIO >>> f = BytesIO() >>> f.write('中文'.encode('utf-8')) 6 >>> print(f.getvalue()) b'\xe4\xb8\xad\xe6\x96\x87' # 可以用一個bytes初始化BytesIO,然后,像讀文件一樣讀取 >>> from io import BytesIO >>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87') >>> f.read() b'\xe4\xb8\xad\xe6\x96\x87'