Python 檔案讀寫(File I/O)

my_file = open('your_file.txt')

text = my_file.read()

print(text) # hello world

my_file.close()

推薦 file i/o 寫法, 使用 with 就不需要使用 file.close() 來關閉檔案

with open('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 寫入)
with open('test.txt', mode = 'w') as my_file:
text = my_file.write('hello, i am brain')
print(text)

錯誤處理

try:
with open('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:
with open('test.txt', 'r') as file:
text = file.read()
translator = Translator(to_lang="zh")
translation = translator.translate(text)
with open('translation.txt', 'w') as my_file2:
my_file2.write(translation)
except (IOError, FileNotFoundError) as err:
print(err)
React Native Beacon 功能開發 Python 基礎語法
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×