Well, I would have done it like this if I understood the question correctly and if I need to save to the file:
in_file = "IN.txt" out_file = "OUT.txt" data_file = [] # ΠΡΠΊΡΡΠ»ΠΈ, ΠΏΡΠΎΡΠΈΡΠ°Π»ΠΈ, ΠΏΠΎΠ»ΡΡΠΈΠ»ΠΈ ΡΠΏΠΈΡΠΎΠΊ with open(in_file, 'r') as read_file: for line in read_file: data_file.append(line.strip('\n')) # Π‘ΠΎΠ΅Π΄ΠΈΠ½ΠΈΠ»ΠΈ ΠΈΠ· ΡΠΏΠΈΡΠΊΠ° Π² ΡΡΡΠΎΠΊΡ, Π·Π°ΠΏΠΈΡΠ°Π»ΠΈ ΠΏΠΎΡΡΡΠΎΡΠ½ΠΎ with open(out_file, 'a') as save_file: tmp_string = '' for num, line in enumerate(data_file): if num % 2 == 0: tmp_string = line continue else: result = '%s - %s\n' % (tmp_string, line) save_file.write(result)
But this is if the lines go one by one in order and never change. Those. is always:
a "text" b "text"
The result will be:
a "text" - b "text" a "text" - b "text"
If there is also a c "text":
in_file = "IN.txt" out_file = "OUT.txt" data_file = [] # ΠΡΠΊΡΡΠ²Π°Π΅ΠΌ ΠΈ ΠΏΠ°ΡΡΠΈΠΌ ΡΠ°ΠΉΠ» with open(in_file, 'r') as read_file: tmp_string = '' # ΠΠ΅ΡΠ΅Π±ΠΈΡΠ°Π΅ΠΌ ΡΠ°ΠΉΠ» ΠΏΠΎ ΡΡΡΠΎΠΊΠ°ΠΌ ΠΈ ΡΡΠ°Π²Π½ΠΈΠ²Π°Π΅ΠΌ Π½Π°ΡΠ°Π»ΡΠ½ΡΠΉ ΡΠΈΠΌΠ²ΠΎΠ»Ρ ΡΡΡΠΎΠΊΠΈ for line in read_file: my_string = line.strip('\n') if my_string[0] == "c": data_file.append(my_string) if my_string[0] == "a": tmp_string = my_string if my_string[0] == "b": tmp_string = '%s - %s' % (tmp_string, my_string) data_file.append(tmp_string) tmp_string = '' # Π‘ΠΎΡ
ΡΠ°Π½ΡΠ΅ΠΌ Π² Π½ΠΎΠ²ΠΎΠΌ ΡΠ°ΠΉΠ»Π΅ with open(out_file, 'a') as save_file: for line in data_file: save_file.write('%s\n' % line)
Of
c "text" a "text" b "text" a "text" b "text" c "text"
We get:
c "text" a "text" - b "text" a "text" - b "text" c "text"