Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading