Future Hendrix Future Hendrix - 6 months ago 28
Python Question

Print from txt file

I have a group of users. I want to scrape the users from a txt file then write

URL GOTO=https://www.url.com/user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27


for each one of them until the users have ran out or all the examples have been replaced, How would I do this?

users.txt

rrralu
rebeccamacavei
corinnaco_
andrew1996_
thisisme_r
zabiburuziga
be_real_00
officiel_14_leo
thefullersgroup


What I have

print("\\reading users")
text_file = open("users.txt", "r")
print(text_file.read())
text_file.close()

Answer

You can use an instance of the built-in string.Template class. Note the $user1 I added.

from string import Template

template = Template('''\
URL GOTO=https://www.url.com/$user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27''')

with open('users.txt') as file:
    for line in file:
        print(template.substitute({'user1': line.strip()}))

Update

An even simpler way is to use the str.format method common to all strings. The syntax for replacement fields is slightly different ({user1} instead of $user1), but it has the advantage that you don't have to import anything to use it and it plays well with all the other format string options.

template = '''\
URL GOTO=https://www.url.com/{user1}
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27'''

with open('users.txt') as file:
    for line in file:
        print(template.format(user1=line.strip()))

Both will product the following output when run with the data in your sample users.txt file:

URL GOTO=https://www.url.com/rrralu
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27
URL GOTO=https://www.url.com/rebeccamacavei
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27
URL GOTO=https://www.url.com/corinnaco_
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27
URL GOTO=https://www.url.com/andrew1996_
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27
URL GOTO=https://www.url.com/thisisme_r
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27
URL GOTO=https://www.url.com/zabiburuziga
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27
URL GOTO=https://www.url.com/be_real_00
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27
URL GOTO=https://www.url.com/officiel_14_leo
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27
URL GOTO=https://www.url.com/thefullersgroup
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow
WAIT SECONDS= 27