如何用 Python 中另一个 txt 文件中的一行替换 txt 文件中的一行
How do I replace a line in a txt file with a line from another txt file in Python
我有两个 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 循环。
谁能帮帮我?
这实际上会对您有所帮助,但再次重申,这是强硬路线,仅适用于您的特定文件
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')
我有两个 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 循环。 谁能帮帮我?
这实际上会对您有所帮助,但再次重申,这是强硬路线,仅适用于您的特定文件
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')