首页 > 编程语言 > 详细

python将两个txt按列合并

时间:2021-02-06 13:40:30      阅读:178      评论:0      收藏:0      [点我收藏+]

技术分享图片要点:

  • 使用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 = []
 
    for m in range(len(file4_list)):
        s=""
        s = "\t".join([file3_list[m],file4_list[m]])
        s+="\n"
        main_file.append(s)

        f=open(folder3 + \\ + years + ‘.txt‘,‘w‘)
        f.writelines(main_file)
        f.close()

python将两个txt按列合并

原文:https://www.cnblogs.com/meijie09/p/14381084.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!