-5

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?

  • 1
    What have you tried so far? – 0x5453 Mar 14 '22 at 17:55
  • 1
    Please, 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 Answers3

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']
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
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 \ns 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