Zion Alt
Zion Alt

Reputation: 27

read from behind in line in the file

I'm basically solving one problem here

with open("input.txt", "r",encoding='ISO-8859-1') as f:
    lines = f.readlines()

I want this code to read one part from the beginning and the other from the end and combine it into one

Here is an example text file I have:

hello i would like to help
I appreciate it really much
maybe I'll pay you back someday
thank you very much for your help

output is new file

    print(line,":",line1, file=open(""+str("treti")+".txt", "a",encoding='utf-8'),sep='')


1 hello i would like to help:thank you very much for your help
2 I appreciate it really much:maybe I'll pay you back someday

Appreciate any help!

Upvotes: 0

Views: 54

Answers (1)

Rabinzel
Rabinzel

Reputation: 7923

There are different ways you can do this. Here are two examples.

In the first one you relate on the index, in the 2nd you just zip the list once from the start and once from the end and add each iteration the lines together.

1) 
for i in range(len(lines)//2):
    s = lines[i].strip()
    e = lines[-1-i].strip()
    print(s, ':', e)

2) 

for i, (line_s, line_e) in enumerate(zip(lines, lines[::-1])):
    if i == len(lines)//2:
        break
    print(f"{line_s.strip()} : {line_e.strip()}")

Ouputs in both:

hello i would like to help : thank you very much for your help
I appreciate it really much : maybe I'll pay you back someday

Upvotes: 1

Related Questions