2

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']
low_ratio
  • 51
  • 5

2 Answers2

2

You can use .rstrip():

data = ['FSDAF\n', 'HKLWF\n', 'AAKEP\n']
print([line.rstrip() for line in data])
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
2

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')
FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28