zoukankan      html  css  js  c++  java
  • 【python】python将两个txt按列合并

    要点:

    • 使用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("{} {}
    ".format(line1.rstrip(), line2.rstrip()))

    以上参考:https://www.cnpython.com/qa/81959

    以下为自己用时的例子
    main_file = []
     
        for m in range(len(file4_list)):
            s=""
            s = " ".join([file3_list[m],file4_list[m]])
            s+=" "
            main_file.append(s)

            f=open(folder3 + '\' + years + '.txt','w')
            f.writelines(main_file)
            f.close()
    本来无一物,何处惹尘埃。
  • 相关阅读:
    【题解】【模板】矩阵级数
    【题解】P2048 [NOI2010]超级钢琴
    【题解】[APIO2009]会议中心
    【题解】[P4178 Tree]
    【题解】扑克牌游戏
    【题解】quake
    【题解】cycle
    从不浪费——分治总结
    【题解】Painting Fence
    【题解】[CJOI2019Chebnear]
  • 原文地址:https://www.cnblogs.com/meijie09/p/14381084.html
Copyright © 2011-2022 走看看