withopen('your_file.text') as my_file: text = my_file.read() print(text)
寫入
open 第二個參數是讀寫模式,
read:r
write:w
append:a
create: x
read and write: r+ (寫入的方式為 Append, 如果你要讀加上覆寫檔案,就只能先用 r mode 讀取再用 w mode 寫入)
withopen('test.txt', mode = 'w') as my_file: text = my_file.write('hello, i am brain') print(text)
錯誤處理
try: withopen('test.txt', mode = 'r') as my_file: print(my_file.read()) except FileNotFoundError as err: print('file does not exist') except IOError as err: print('IO error') raise err
練習
利用 translate 套件,讀取英文檔案後翻譯成中文, 寫入另一個檔案
from translate import Translator
translation = '' try: withopen('test.txt', 'r') as file: text = file.read() translator = Translator(to_lang="zh") translation = translator.translate(text) withopen('translation.txt', 'w') as my_file2: my_file2.write(translation) except (IOError, FileNotFoundError) as err: print(err)