Need help - code does not read lines of lists contained in txt file into what we want

Dear,

I am encounter a problem when reading a list saved in txt:

I have python program which generates random number sets and saved them into 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:
[
5
,
2
6
,
3
9
]

Instead of what i want below:
[5,
26,
39]

It seems the code is reading each character instead of a number itselt.

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

open ( file , mode=‘r’ , buffering=-1 , encoding=None , errors=None , newline=None , closefd=True , opener=None )`
open

The file name is the first parameter, with no mention of modifier prefix. What does the r stand for? Is it something like b"file.txt"?

Hi,

Thanks. If I dont have that “r” then the code will give me error of:
SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape

I dont remember where i read about this and somebody mentioned that i should add a r before the path. And then the error goes away…

Sorry I am still learning and i dont know the reason behind this.

And now we are both learning. The evidence is that we might step back and fill in all the holes where our understanding is at the bottom and needing to be elevated to level ground.

Can you find any documentation that relates to this?

1 Like

I read it here:

Something related to converting normal string to raw string

1 Like

Oh i might misled you, in my path

open(r"201219.txt", 'r')

I deleted my folder path on my PC.

It all makes sense when the cards are on the table. Thanks for digging!

Back to the outputting problem, it must relate to the output stream. One will have to find a way to interdict the default behavior and bend it to one’s own liking. At least we know we have a stream, so can move forward from here.

Easiest way is to transform the input stream to a fixed object. Stream the input to a list or some form of collection that can be iterated later.

I tried to use a sample txt with only words:
one
two
three

but the code still return
o
n
e
t
w
o

if I try to print… I am not sure where the problem is…