Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a list with a newline?

Tags:

python

list

In the following code I am updating a list with two items by appending to it from within a for loop. I need a newline to be added after appending each string but I can't seem to be able to do it.

I thought it would have been:

lines = []
for i in range(10):

    line = ser.readline()
    if line:
        lines.append(line + '\n')             #'\n' newline 
        lines.append(datetime.now())

But this only adds the '\n' as a string. I have also tried the same without without the quotes, but no luck.

I am getting this:

['leftRaw; 928090;   0;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;      0.00;  0.00;\n', datetime.datetime(2016, 8, 25, 23, 48, 4, 517000), '\r\x00rightRaw; 928090;   0;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;\n', datetime.datetime(2016, 8, 25, 23, 48, 4, 519000), '\r\x00leftRaw; 928091;   0;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00)]

But I want this:

['leftRaw; 928090;   0;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;\n', 
datetime.datetime(2016, 8, 25, 23, 48, 4, 517000), 
'\r\x00rightRaw; 928090;   0;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;\n', 
datetime.datetime(2016, 8, 25, 23, 48, 4, 519000)]

Any ideas?

like image 628
Steve Avatar asked Jan 24 '26 05:01

Steve


2 Answers

I fixed the issue by appending datetime.now to the list as a string on every frame using the strftime method. I was then able to add newlines with lines = '\n'.join(lines). See code below for the working code.

lines = []
for frame in range(frames):
    line = ser.readline()
    if line:
        lines.append(line)
        lines.append(datetime.now().strftime('%H:%M:%S'))

lines = '\n'.join(lines)

dataFile.write('%s'%(lines))

This gives me the desired output of each list item on a new line e.g.

['leftRaw; 928090;   0;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;\n', 
datetime.datetime(2016, 8, 25, 23, 48, 4, 517000), 
'\r\x00rightRaw; 928090;   0;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;  0.00;\n', 
datetime.datetime(2016, 8, 25, 23, 48, 4, 519000)']
like image 106
Steve Avatar answered Jan 26 '26 18:01

Steve


You can add all items to the list, then use .join() function to add new line between each item in the list:

for i in range(10):
    line = ser.readline()
    if line:
        lines.append(line)
        lines.append(datetime.now())
final_string = '\n'.join(lines)
like image 24
anderson_berg Avatar answered Jan 26 '26 20:01

anderson_berg