Max Kraus Max Kraus - 5 months ago 13
Python Question

Python read .txt File -> list

I have a .txt File and I want to get the values in a list.
The format of the txt file should be:

value0,timestamp0
value1,timestamp1
...
...
...


In the end I want to get a list with

[[value0,timestamp0],[value1,timestamp1],.....]


I know it's easy to get these values by

direction = []
for line in open(filename):
direction,t = line.strip().split(',')
direction = float(direction)
t = long(t)
direction.append([direction,t])
return direction


But I have a big problem: When creating the data I forgot to insert a "\n" in each row.

Thats why I have this format:

value0, timestamp0value1,timestamp1value2,timestamp2value3.....


Every timestamp has exactly 13 characters.

Is there a way to get these data in a list as I want it? Would be very much work get the data again.

Thanks
Max

Answer

I coded a quickie using your example, and not using 13 but len("timestamp") so you can adapt

instr = "value,timestampvalue2,timestampvalue3,timestampvalue4,timestamp"

previous_i = 0
for i,c in enumerate(instr):
    if c==",":
        next_i = i+len("timestamp")+1
        print(instr[previous_i:next_i])
        previous_i = next_i

output is descrambled:

value,timestamp
value2,timestamp
value3,timestamp
value4,timestamp