python 的文件读取与合并。可以读取特定行数的文件。
#创建temp1.txt,将1~100存入其中
with open ('./temp1.txt','w',encoding='UTF-8') as f1:
for i in range(1,101):
f1.write(str(i)+'\n')
#创建temp2.txt,将200~499存入其中
with open ('./temp2.txt','w',encoding='UTF-8') as f2:
for i in range(200,500):
f2.write(str(i)+'\n')
#将2个文件合并
#read可以一次读取所有内容,返回的是字符串
with open ('./temp1.txt','r',encoding='UTF-8') as f3:
temp1_text=f3.read()
#读取temp2中的前100行,注意返回的是一个列表
with open ('./temp2.txt','r',encoding='UTF-8') as f4:
temp2_text=f4.readlines()[:100]
#将1~100,200~299存入temp5.txt中
with open ('./temp5.txt','w',encoding='UTF-8') as f5:
f5.write(temp1_text)
for line in temp2_text:
f5.write(line)