Python wrong data from file opening

40 Views Asked by At

In python digits inside my text file are present in lines. Such as:

1
2
3

When I try to get data from file through readlines() after every digit \n becomes part of that element in list however in such as:

['1\n','2\n' ]

However in tutorial it does not add \n after every digit. Can anybody explain why it happens and it's solution plz

I was expecting the result should be:

[1,2,3,4]
1

There are 1 best solutions below

4
Ilya On

Try this, its very ugly method, but it will solve your problem:)

    with open(‘123.txt’, ‘r’) as rf:
       lines = rf.readlines()
       result = []
       for elem in lines:
           result.append(int(elem))