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:
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