0

I have a script that finds usernames and saves it to a file. I want to convert the usernames in accounts.txt to a list. I am unsure how to do this... Does anyone know how to help?

accounts.txt

@example1
@example2
@example3
@example4
@example5
@example6

What I want my program to create from accounts.txt:

['example1', 'example2', 'example3', 'example4', 'example5', 'example6']
  • 3
    each stripped line of the file should be an element of the list. What did you try? – DirtyBit Sep 09 '20 at 14:17
  • I am not sure where to start... @DirtyBit –  Sep 09 '20 at 14:20
  • 2
    Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – mooga Sep 09 '20 at 14:21

3 Answers3

1

try something like this?

my_list = []

with open("accounts.txt", "r") as file:
    for line in file:
        my_list.extend(line.split())
my_list = [s[1:] for s in my_list]


print(my_list)

will print this: ['example1', 'example2', 'example3', 'example4', 'example5', 'example6']

mastercool
  • 463
  • 12
  • 35
0

Read the file using readlines() and then strip each line using list-comprehension:

with open("accounts.txt") as fileObj:
    content = fileObj.readlines()

# getting rid of the empty lines
file_data = [x.strip() for x in content] 
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

You have to read each line and remove first `@' character and add in the list.
Try below code

with open("accounts.txt","r") as f:
    print([a[1:].strip() for a in f])

Output

['example1', 'example2', 'example3', 'example4', 'example5', 'example6']
Liju
  • 2,273
  • 3
  • 6
  • 21