Steve
Steve

Reputation: 327

How to 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?

Upvotes: 3

Views: 88527

Answers (3)

Steve
Steve

Reputation: 327

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

Upvotes: 4

Jake Askeland
Jake Askeland

Reputation: 273

It looks like the lines list is simple being printed in its entirety. The \n you see is only printing as an indicator that there are in fact new-lines. See this smaller example:

In [18]: print ['asdf' + '\n\n'] + [datetime.now()],
['asdf\n\n', datetime.datetime(2016, 8, 25, 15, 32, 5, 955895)]
In [19]: a = ['asdf' + '\n\n', datetime.now()]
In [20]: print a[0]
asdf

In [21]: print a
['asdf\n\n', datetime.datetime(2016, 8, 25, 15, 37, 14, 330440)]

In [22]:

Upvotes: 0

anderson_berg
anderson_berg

Reputation: 27

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)

Upvotes: 1

Related Questions