首页 > 解决方案 > python - 如何用Python中另一个txt文件中的一行替换txt文件中的一行

问题描述

我有两个txt文件:

Dummy-dates.txt contains:
0/0/0000|
1/0/0000|
2/0/0000|
etc... up to 31.

single-dates.txt contains:
2/0/0000|Johns Bday
6/0/0000|Some other cool date
etc.. can have random number of lines within 1-31 in the start

I need to create a new txt file containing:
0/0/0000|
1/0/0000|
2/0/0000|Johns Bday
3/0/0000|
4/0/0000|
5/0/0000|
6/0/0000|Some other cool date
7/0/0000|
etc.... up to 31

我无法弄清楚 - 我尝试过使用嵌套的 for 循环。谁能帮我吗?

标签: pythonmergetxt

解决方案


这实际上会对您有所帮助,但再一次,这很难说,仅适用于您的特定文件

def get_line(file_name1,file_name2, line_start1,line_end1, line_start2, line_end2, file_name3):
    f1 = open(file_name1, 'r+')
    f2= open(file_name2, 'r+')
    f3=open(file_name3,'w+')
    line1=f1.readlines(line_start1)    
    line2=f2.readlines(line_start2)
    line1=line1[:line_end1]
    line2=line2[:line_end2]
    for i in range(len(line2)):
      line3="".join(line2[i].split("|")[0]).replace("/","")
      for k in range(len(line1)):
        line4="".join(line1[k].split("|")[0]).replace("/","")
        if(line3==(line4)):
          line1[k]=line2[i]
    f3.writelines(line1)
    f1.close()
    f2.close()
    f3.close()

get_line('temp/Dummy-dates-1.txt', 'temp/Separate-dates-1.txt', 0, 31, 0, 31, 'temp/Combined-1.txt')

推荐阅读