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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x