Reputation: 53
I want to replace the word "example" on textfile2.txt with a list of words from textfile1.txt until the list runs out or all the "example" have all been replaced then I want to display the whole finished text.
How would I do this?
textfile1.txt
user1
user2
textfile2.txt
URL GOTO=https://www.url.com/example
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
URL GOTO=https://www.url.com/example
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
Current code:
with open('textfile1.txt') as f1, open('textfile2.txt') as f2:
for l, r in zip(f1, f2):
print(r[:r.find('/example') + 1] + l)
Results it gives me:
URL GOTO=https://www.instagram.com/user1
user2
Goal:
URL GOTO=https://www.url.com/user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
URL GOTO=https://www.url.com/user2
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
Upvotes: 1
Views: 85
Reputation: 430
here is the my solution:
with open('t1.txt') as f1, open('t2.txt') as f2:
url_info = f2.read().split('\n\n')
users = f1.read().split('\n')
zipped_list = zip(users, url_info)
for item in zipped_list:
print item[1].replace('example', item[0])+"\n"
updated: this need import itertools
import itertools
with open('t1.txt') as f1, open('t2.txt') as f2:
url_info = f2.read().split('\n\n')
users = [u for u in f1.read().split('\n') if u]
zipped_list = list(itertools.izip(url_info, itertools.cycle(users)))
for item in zipped_list:
print item[0].replace('example', item[1])+"\n"
output:
URL GOTO=https://www.url.com/user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
URL GOTO=https://www.url.com/user2
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
URL GOTO=https://www.url.com/user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
Upvotes: 3