讀文件
def read_file(filepath):
with open(filepath, 'r', encoding='utf-8') as file:
for line in file:
print(line)
寫文件
def write_file(filepath):
with open(filepath, 'w', encoding='utf-8') as file:
file.write('hello world')
讀寫文件
def read_write_file(filepath):
with open(filepath, 'r+', encoding='utf-8') as file:
text = file.read()
# 處理文本
text = re.sub('python', 'python3', text)
# 默認(rèn)是在最后追加,以下方法可覆蓋
file.seek(0)
file.truncate()
# 寫入
file.write(text)
https://stackoverflow.com/a/13464228/3355097
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。