-1

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]
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    The tutorial is wrong or you misread it. `readlines()` includes the newlines that separate the lines in its result. And why do you expect a list of numbers? Files contain text, you have to call `int()` to convert it to numbers. – Barmar Jul 13 '23 at 05:02
  • 1
    Reading from a file will never result in a list of numbers without some additional processing. Are you sure your tutorial didn’t include some extra steps? – deceze Jul 13 '23 at 05:02
  • What is the URL of the tutorial? – Barmar Jul 13 '23 at 05:03

1 Answers1

0

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))

Ilya
  • 5
  • 5
  • 1
    FWIW, the probably more pythonic implementation of this approach would be `result = list(map(int, rf))`. – deceze Jul 13 '23 at 05:17
  • @ deceze ♦ I think this is the case when the easier the better :D – Ilya Jul 13 '23 at 05:25
  • @Ilya "Easy" lies in the eyes of the beholder. For me, the easier version is the one that deceze has shown. – Matthias Jul 13 '23 at 06:38
  • @Matthias It seems to me that for a beginner, who is the creator of the question, it is better to understand the basic functions of the language before moving on to something more correct, but also more difficult to understand. But after all I agree with you:) – Ilya Jul 13 '23 at 06:50