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

Print line above specific string from txt file

I have txt file contains data, i want to loop over file and print only line above "City" word.

Ex of txt file:

NEW FUSTAT TOURS
City
USA
Addres
napolean
Phone Number
************
Email
***************
PACKAGES
Test TOURS
City
UK
Addres
napolean
Phone Number
************
Email
***************
PACKAGES

Result Expected:

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

NEW FUSTAT TOURS
Test TOURS

I tried:

with open('dd.txt', 'r', encoding="utf-8") as f:
    input_file = f.readlines()
    for i, line in enumerate(input_file):
        if 'City' in line:
            f1 = (input_file[:i])
            f2 = str(f1)
            f3 = (f2.replace("['", ''))
            f4 = (f3.replace("\\n']", ''))
            print(f4)

Result:

NEW FUSTAT TOURS
NEW FUSTAT TOURS\n', 'City\n', 'USA\n', 'Addres\n', 'napolean\n', 'Phone Number\n', '************\n', 'Email\n', '***************\n', 'PACKAGES\n', 'Test TOURS

Any kind of help please?

>Solution :

with open('dd.txt', 'r', encoding="utf-8") as f:
    line = ''
    for next_line in f:
        if next_line.startswith('City'):
            print(line)
        line = next_line.strip()

EDIT:

with open('dd.txt') as f, open('out.txt', 'w') as f_out:
    line = ''
    for next_line in f:
        if next_line.startswith('City'):
            f_out.write(line)
        line = next_line
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