Reading a txt file into a list without newlines in python

Viewed 83

I have a txt file that looks like this:

FSDAF  
HKLWF  
AAKEP  

How can I read that into a list so it looks like this: lst = ['FSDAF', 'HKLWF', 'AAKEP']
I did something like this but I cant get rid of the newlines:

file = open('dane.txt', 'r')
lst = file.readlines()

And it displays the newlines like this:

['FSDAF\n', 'HKLWF\n', 'AAKEP\n']
2 Answers

You can use .rstrip():

data = ['FSDAF\n', 'HKLWF\n', 'AAKEP\n']
print([line.rstrip() for line in data])

You can open it...

with open('dane.txt', 'r') as file:
    ...

...then (into the with/as block) read the file...

content = file.read()

...then split it into a list:

myList = content.split('\n')
Related