要点:
- 使用
with
打开文件。不需要关闭文件。 - 使用
zip
函数组合两个列表。
不带zip的代码,带内联注释:
combine =[]
with open("x.txt") as xh:
with open('y.txt') as yh:
with open("z.txt","w") as zh:
#Read first
file
xlines = xh.readlines()
#Read second file
ylines = yh.readlines()
#Combine content of both lists
#combine = list(zip(ylines,xlines))
#Write to third file
for i in range(len(xlines)):
line = ylines[i].strip() + ' ' + xlines[i]
zh.write(line)
zip带有编码功能的
with open("x.txt") as xh:
with open('y.txt') as yh:
with open("z.txt","w") as zh:
#Read first file
xlines = xh.readlines()
#Read second file
ylines = yh.readlines()
#Combine content of both lists and Write to third file
for line1, line2 in zip(ylines, xlines):
zh.write("{} {}\n".format(line1.rstrip(), line2.rstrip()))
以上参考:https://www.cnpython.com/qa/81959
以下为自己用时的例子
main_file = []
forinrange(len(file4_list)):
""
s = "\t".join([file3_list[m],file4_list[m]])
s+="\n"
main_file.append(s)
open(folder3 + '\\''.txt','w')
f.writelines(main_file)
f.close()
本来无一物,何处惹尘埃。