Issue
I have two txt files, the first one contains duplicated word "PACKAGES", i want to replace each "PACKAGES" word with a line from file 2
Ex of file 1:
NEW FUSTAT TOURS
City
USA
Address
napolean
PACKAGES
Test TOURS
City
UK
Address
napolean
PACKAGES
Ex of file 2:
First Company
Second Company
Expected Output:
NEW FUSTAT TOURS
City
USA
Address
napolean
First Company
Test TOURS
City
UK
Address
napolean
Second Company
I tried:
with open("file1.txt", encoding="utf-8") as first, open("file2.txt", encoding="utf-8") as second:
first_file = first.read()
second_file = second.readline()
print(first_file.replace('PACKAGES', second_file))
Result:
NEW FUSTAT TOURS
City
USA
Addres
napolean
Phone Number
************
Email
***************
First Company
Test TOURS
City
UK
Addres
napolean
Phone Number
************
Email
***************
First Company
Any kind of help please?
Solution
Here's one way you could do it:
with open('file1.txt', encoding='utf-8') as f1:
with open('file2.txt', encoding='utf-8') as f2:
f2lines = iter(f2.readlines())
for f1line in f1:
if f1line.startswith('PACKAGES'):
print(next(f2lines), end='')
else:
print(f1line, end='')
Output:
NEW FUSTAT TOURS
City
USA
Address
napolean
First Company
Test TOURS
City
UK
Address
napolean
Second Company
Answered By - Olvin Roght
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.