0

I am self learning python and I encountered a problem when my code tries reading a list saved in txt:

I have a series of number sets saved in the txt: for example the data in txt is as follow:

[5,26,39]

[7,21,40] …

I have tried the following 2 codes to read the above txt:

data = open(r"201219.txt", 'r')
lines = data.readlines()
for line in lines:
    for i in line:
        print(i)

AND

with open(r"201219.txt", 'r') as data:
lines = data.read().splitlines()
for line in lines:
    for i in line:
        print(i)

Both of the above codes will print something like: enter image description here

It seems the code is reading each character instead of a number itself. I can't iterate through the items as it is not what I want.

Does anyone know how to deal with this? Thanks very very much.

  • A text file is just a sequence of characters -- it has no internal organization other than lines. It doesn't know that `26` is supposed to be the number 26; it just sees the character `2`, followed by the character `6`, followed by whatever character is next. If you have the capability to change how the data is saved, then I think json would be a much better format. – John Gordon Dec 26 '20 at 01:33
  • Basically, you have to read and understand how to strip the delimiters to parse the numbers correctly: lines = data.readlines(); print(lines); for line in lines: ll = line.lstrip('[').rstrip(']\n').split(','); print(ll); – Daniel Hao Dec 26 '20 at 02:19
  • Guys, thanks for helping me. Those are very helpful – Derek Chen Dec 28 '20 at 01:58
  • Ifinally found that i can save the data by using .pkl format which can keep the data structure of the output. problem solved. Thanks! – Derek Chen Dec 28 '20 at 01:59

0 Answers0