Steve Steve - 3 months ago 23
Python Question

Python: Append a list with a newline

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?

Answer

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