Python 3.x 仅当python中的两行连续行开始时合并,并正常写入其余文本

Python 3.x 仅当python中的两行连续行开始时合并,并正常写入其余文本,python-3.x,Python 3.x,输入 代码 您好,我有一个代码,搜索两个连续的行是否从03110开始并打印这些行,但我想转换代码,以便它打印或在.txt处写入其余行 输出应该是这样的 prev = '' with open('out.txt') as f: for line in f: if prev.startswith('03110') and line.startswith('03110'): print(prev.strip()+ '|03100|XX|PARCELA|'

输入

代码

您好,我有一个代码,搜索两个连续的行是否从03110开始并打印这些行,但我想转换代码,以便它打印或在.txt处写入其余行

输出应该是这样的

prev = ''
with open('out.txt') as f:
    for line in f:
        if prev.startswith('03110') and line.startswith('03110'):
            print(prev.strip()+ '|03100|XX|PARCELA|' + line)
        prev = line
我知道我只合并了这两行,因为这是print()的命令


但是我不知道如何进行desire输出,有人能帮我编写代码吗?

您的代码加入行,但我得到了第一行03110的重复行。您的代码加入行,但保留前03110,我希望喜欢输出。我说清楚了吗?你能帮我吗?好的,现在应该可以了。我忘了添加
elif语句
您的代码加入行,但我得到了第一行03110的重复行。您的代码加入行,但保留前03110,我希望喜欢输出。我说清楚了吗?你能帮我吗?好的,现在应该可以了。我忘了添加
elif语句
03110|||1299,00|00|3100|XX|PARCELA|03110||||7761,00|00|
02000|42163,54|
03100|4|6070,00
03110|||6070,00|00|00|
00000|31751150201912001|01072000600074639|
02000|288465,76|
03100|11|9060,00
03110|||1299,00|00|3100|XX|PARCELA|03110||||7761,00|00|
03100|29|14031,21
03110|||14031,21|00|
00000|31757328201912001|01072000601021393|
03110|||1299,00|00|3100|XX|PARCELA|03110||||7761,00|00|
# I assume the input is in a text file:
with open('myFile.txt', 'r') as my_file:
    splited_line = [line.rstrip().split('|') for line in my_file] # this will split every line as a separate list
    new_list = []
    for i in range(len(splited_line)):
       try:
         if splited_line[i][0] == '03110' and splited_line[i-1][0] == '03110': # if the current line and the previous line start with 03110
            first = '|'.join(splited_line[i-1])
            second = '|'.join(splited_line[i])
            newLine = first + "|03100|XX|PARCELA|"+ second
            new_list.append(newLine)
         elif splited_line[i][0] == '03110' and splited_line[i+1][0] == '03110': # to escape duplicating in the list
            pass
         else:
            line = '|'.join(splited_line[i])
            new_list.append(line)
       except IndexError:
          pass

   #  To write the new_list to text files

    with open('new_file' , 'a') as f:
      for item in new_list:
         print(item)
         f.write(item + '\n')