【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("{} {}\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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM