【hisword2017】Pyhon Notebook - 文本讀寫
讀取檔案
# 打開方式1
file_open = open('menu.txt','r',encoding = 'utf-8')
rlines = file_open.readlines()
#rlines is a list
for line in rlines:
print(line)
#close the file
file_open.close()
# 打開方式2,這種格式不用打開檔案之后再關閉檔案,程式自動關閉
with open('menu.txt','r',encoding = 'utf-8') as file_open:
rlines = file_open.readlines()
for line in rlines:
print(line)
寫入檔案
# 寫入方式1
file_open = open('menu.txt','w',encoding = 'utf-8')
#把字串串列寫入檔案
file_open.writelines(list)
file_open.close()
# 寫入方式2
# 這種格式不用關閉檔案,程式自動關閉
with open('menu.txt','w',encoding = 'utf-8') as file_open:
file_open.wrtielines(list)
例子1 替換文本中的詩句
目標:
1,poem.txt中有一首詩,
2,test.txt中老師有幾句需要學生默寫的句子
4,poem.txt中找到text.txt中指出的句子,替換掉 __________,
poem.txt 內容:
登高 杜甫
風急天高猿嘯哀,
渚清沙白鳥飛回,
無邊落木蕭蕭下,
不盡長江滾滾來,
萬里悲秋常作客,
百年多病獨登臺,
艱難苦恨繁霜鬢,
潦倒新停濁酒杯,
text.txt 內容:
無邊落木蕭蕭下,
不盡長江滾滾來,
#step 1: 讀取 poem.txt檔案
with open('poem.txt','r',encoding = 'utf-8') as poem_file:
readline_list = poem_file.readlines()
with open('text.txt','r',encoding = 'utf-8') as poem_file2:
readline_list2 = poem_file2.readlines()
with open('poem2.txt','w',encoding = 'utf-8') as poem_file3:
for line in readline_list:
if line in readline_list2:
poem_file3.write('_______________\n')
else:
poem_file3.write(line)
結果:
poem2.txt
登高 杜甫
風急天高猿嘯哀,
渚清沙白鳥飛回,
______________.
______________.
萬里悲秋常作客,
百年多病獨登臺,
艱難苦恨繁霜鬢,
潦倒新停濁酒杯,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/240975.html
標籤:其他
上一篇:CKA-題庫-簡潔參考答案
下一篇:[Oracle]見習BI工程師
