【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,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
登高 杜甫
风急天高猿啸哀,
渚清沙白鸟飞回。
______________.
______________.
万里悲秋常作客,
百年多病独登台。
艰难苦恨繁霜鬓,
潦倒新停浊酒杯。