1. 程式人生 > >python txt基本操作

python txt基本操作

如下表

模式 可做操作 若檔案不存在 是否覆蓋
r 只能讀 報錯 -
r+ 可讀可寫 報錯
w 只能寫 建立
w+  可讀可寫 建立
a   只能寫 建立 否,追加寫
a+ 可讀可寫 建立 否,追加寫

 

Example1:

import re
f1 = open('./test.txt')
f2 = open('./my.txt','r+')
for s in f1.readlines():
f2.write(s.replace('hello','hi'))
f1.close()
f2.close()