PYTHON機器學習自學/自修 整理[00027] ~ PYTHON – 100天从新手到大师(11.文件和异常.md)
PYTHON機器學習自學/自修 整理[00027] ~ PYTHON – 100天从新手到大师(11.文件和异常.md)
‘r’ 讀取(默認)
‘w’ 寫入(會先截斷之前的內容)
‘x’ 寫入,如果文件已經存在會產生異常
‘a’ 追加,將內容寫入到已有文件的末尾
‘b’ 二進制模式
‘t’ 文本模式(默認)
‘+’ 更新(既可以讀又可以寫)
單純開檔+讀檔(全部)最後顯示檔案內容
def main(): f = None try: f = open('致橡树.txt', 'r', encoding='utf-8') print(f.read()) except FileNotFoundError: print('无法打开指定的文件!') except LookupError: print('指定了未知的编码!') except UnicodeDecodeError: print('读取文件时解码错误!') finally: if f: f.close() if __name__ == '__main__': main()
單純開檔+讀檔(一行一行)最後顯示檔案內容
import time def main(): # 一次性读取整个文件内容 with open('致橡树.txt', 'r', encoding='utf-8') as f: print(f.read()) # 通过for-in循环逐行读取 with open('致橡树.txt', mode='r') as f: for line in f: print(line, end='') time.sleep(0.5) print() # 读取文件按行读取到列表中 with open('致橡树.txt') as f: lines = f.readlines() print(lines) if __name__ == '__main__': main()
依序打開三個檔案,並且寫入對應資訊
from math import sqrt def is_prime(n): """判断素数(質數)的函数""" assert n > 0 for factor in range(2, int(sqrt(n)) + 1): if n % factor == 0: return False return True if n != 1 else False def main(): filenames = ('a.txt', 'b.txt', 'c.txt') fs_list = [] try: for filename in filenames: fs_list.append(open(filename, 'w', encoding='utf-8'))#依序開檔,並把開檔後的檔案變數放到陣列之中 for number in range(1, 10000): if is_prime(number): if number < 100:#1~99質數 fs_list[0].write(str(number) + '\n') elif number < 1000:#100~999質數 fs_list[1].write(str(number) + '\n') else: fs_list[2].write(str(number) + '\n') except IOError as ex: print(ex) print('写文件时发生错误!') finally: for fs in fs_list:#依序關閉檔案 fs.close() print('操作完成!') if __name__ == '__main__': main()
讀寫二進制檔(簡易圖檔複製)
def main(): try: with open('guido.jpg', 'rb') as fs1: data = fs1.read() print(type(data)) # <class 'bytes'> with open('吉多.jpg', 'wb') as fs2: fs2.write(data) except FileNotFoundError as e: print('指定的文件无法打开.') except IOError as e: print('读写文件时出现错误.') print('程序执行结束.') if __name__ == '__main__': main()