简体   繁体   中英

How do I replace a line in a txt file with a line from another txt file in Python

I have two txt files:

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

I can not figure this out - I've tried with a nested for loop. Can anyone help me out?

This actually will help you, but once again, this is hard line, only for your specific file

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM