I have a file with usernames, each username is on a new line, im trying to convert it to a list with python, how do I do that?
Asked
Active
Viewed 2,081 times
-5
-
1What have you tried so far? – 0x5453 Mar 14 '22 at 17:55
-
1Please, check [ask]. Post [mre] of your code and ask a question about specific problem with your code. – buran Mar 14 '22 at 17:57
-
@0x5453 ive tried to do "usernames = list(map(str.split, f.read().split('\n\n')))" but it gives me a list which is only 1 item in length, ive atached an example [here](https://fileportal.org/CAA4jabQ1GESRGcSDAGLxLAZyrmIfxtXBLtEU8KuEOsxTg) – Artyom Kulimov Mar 14 '22 at 18:00
-
You're overcomplicating things. Why do you split with two newline characters? – Matthias Mar 14 '22 at 18:02
-
If you open your file with `with open (your_filename_here) as f:` then it's a simple `usernames = [line.strip() for line in f]` to read everything and to strip spaces and newline characters. – Matthias Mar 14 '22 at 18:04
3 Answers
2
I'm assuming you have a file with usernames in the below format.
users.txt
user1
user2
user3
user4
sample python code is:
with open("users.txt") as f:
lines = [line.rstrip('\n') for line in f]
print(type(lines))
print(lines)
Output:
<class 'list'>
['user1', 'user2', 'user3', 'user4']

sujit patel
- 38
- 6
1
#read s.txt file
fp=open("s.txt","r")
s=fp.read()
usernamesarr=s.split("\n")
print(usernamesarr)
output:
[naveenkumar,sethu,logan]
s.txt
naveenkumar
sethu
logan
Think I have understood your question.

Naveenkumar M
- 616
- 3
- 17
-
this is too complicated. and it will give you strings. it cant give you list of variables as output – Balla Botond Mar 14 '22 at 17:59
-
0
- Open the file
- use the function
x.readlines()
- DONE!
Example:
file = open("r", "usernames.txt")
listofusernames = file.readlines()
file.close()
print(listofusernames)
And the output will be:
["User1\n", "User2\n", "User3\n"]
If you don't want the \n
s there after most of the elements, you need
rep = []
for x in listofusernames:
rep.append(x.replace("\n", ""))
print(list(rep))
so the full code will be:
file = open("r", "usernames.txt")
listofusernames = file.readlines()
file.close()
rep = []
for x in listofusernames:
rep.append(x.replace("\n", ""))
print(list(rep))
And now the output will be correct, sorry for my error

Balla Botond
- 55
- 11
-
-
Sorry? I have used this code like a hundred times, and its working fine – Balla Botond Mar 14 '22 at 18:01
-
hey, thanks for the answer, the list is created but there is a "\n" at the end of each element inside the list, how do i remove it? – Artyom Kulimov Mar 14 '22 at 18:05
-
2@BallaBotond That's obviously wrong. There's a newline at the end of each string. How could this even run if you start with an error in the first line (switched parameters)? – Matthias Mar 14 '22 at 18:06