I'm making a simple script on Python 3. I have a list of usernames, colors and numbers. Each of them separated by lines in a .txt file, like this:
Files image:
This is the code:
user = open('user.txt', 'r').readlines()
color = open('color.txt', 'r').readlines()
number = open('number.txt', 'r').readlines()
for u in user:
for c in color:
for n in number:
generated = u c n
print(generated)
open('generated.txt', 'a ').write(generated)
First 100 outputs: https://pastebin.com/Dc07ApbL
But I want something like this:
solvethisproblem_userwhite1
solvethisproblem_userwhite2
solvethisproblem_userwhite3
solvethisproblem_userwhite4
solvethisproblem_userwhite5
solvethisproblem_userwhite6
solvethisproblem_userwhite7
solvethisproblem_userwhite8
solvethisproblem_userwhite9
solvethisproblem_userwhite10
solvethisproblem_userblack1
solvethisproblem_userblack2
solvethisproblem_userblack3
solvethisproblem_userblack4
solvethisproblem_userblack5
solvethisproblem_userblack6
solvethisproblem_userblack7
solvethisproblem_userblack8
solvethisproblem_userblack9
solvethisproblem_userblack10
solvethisproblem_useryellow1
solvethisproblem_useryellow2
solvethisproblem_useryellow3
CodePudding user response:
Using str.rstrip
gets rid of the newline character and any whitespace at the end of the string:
generated = ''.join(map(str.rstrip, [u, c, n]))
CodePudding user response:
Simply replace
user = open('user.txt', 'r').readlines()
color = open('color.txt', 'r').readlines()
number = open('number.txt', 'r').readlines()
with
user = open('user.txt', 'r').read().splitlines()
color = open('color.txt', 'r').read().splitlines()
number = open('number.txt', 'r').read().splitlines()
and replace generated = u c n
with generated = u c n "\n"
.
The str.splitlines()
method removes the \n
characters that would cause the newlines.
But do note that is is better practice to use the with
keyword to open your files:
with open('user.txt') as u, open('color.txt') as c, open('number.txt') as n:
user = u.read().splitlines()
color = c.read().splitlines()
number = n.read().splitlines()