4

I want to take a list of words from textfile1.txt and replace the word "example" on textfile2.txt to whatever the text is on line one, line two and so on.. How would I do this?

Text file textfile1.txt

user1
user2
user3
user4
user5

Text file textfile2.txt

url/example
url/example
url/example
url/example
url/example

What I have so far

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput("textfile2.txt", inplace=True ) as file:
    for line in file:
        print(line.replace("example", "user1"), end='')

My goal:

url/user1
url/user2
url/user3

2 Answers 2

4

This should do it. In general, when you want to traverse 2 or more iterables (lists, files, etc) in parallel, odds are you can use zip.

with open('textfile1.txt') as f1, open('textfile2.txt') as f2:
    for l, r in zip(f1, f2):
        print(r[:r.find('/')+1] + l)
Sign up to request clarification or add additional context in comments.

4 Comments

Good. But perhaps use izip (or Python 3) so the entire contents of 2 files does not need to be read...
you meant print(r[:r.find('/')+1] + l)
Heh yes I did, @Moses Koledoye. dawg, the OP is using Python 3 but you have a point.
Worked perfectly! Thanks bro but I've ran into another problem, whenever I run it to replace "example" it just outputs user1 instead of: URL GOTO=URL.com/example TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow WAIT SECONDS= 2712 what am I missing here? I changed the code to print(r[:r.find('/example')+1] + l) btw
0

I would open the first file and read each line into an array: ['user1', 'user2', ...]

Then, as you read the 2nd file, keep track of your line number. Index into the array based on the line number and use that string as your replacement string.

Or use the zip() answer, which is also fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.