在正确的位置将数据写入csv?

时间:2017-09-07 22:44:01

标签: python python-3.x csv

import csv
import datetime
from time import strftime
now = [strftime('%Y-%m-%d %H:%M:%S')]
t = datetime.datetime.now()
a=[100,101,102,103,104]
b=[86,87,88,89,90]
c=[95,96,97,98,99]
d=[71,72,73,74,75]
with open('ddd.csv', 'a',newline='') as output_file:
    writer = csv.writer(output_file, delimiter=',')
    writer.writerow(now)
    writer.writerow(a)
    writer.writerow(b)
    writer.writerow(c)
    writer.writerow(d)

在这种情况下,它将输出图片1.我不想要图片1。

screenshot 1

我需要在图片2中写下数字。

screenshot 2

如何将数据写入我想要的位置?

我不想使用[" ","71","72","73","74","75"]来制作它。如果数据比以前更多,我想我将以这种方式面临另一个问题。

2 个答案:

答案 0 :(得分:0)

with open('ddd.csv', 'a',newline='') as output_file:
    writer = csv.writer(output_file, delimiter=',')
    writer.writerow([now] + a)
    writer.writerow([None] + b)
    writer.writerow([None] + c)
    writer.writerow([None] + d)

喜欢这个吗?

答案 1 :(得分:0)

如果你想要一个主要是空白的列,那就按行生成:

import csv
import time

now = time.strftime('%Y-%m-%d %H:%M:%S')
rows = [[now,100,101,102,103,104],
        ['',86,87,88,89,90],
        ['',95,96,97,98,99],
        ['',71,72,73,74,75]]
with open('ddd.csv','w',newline='') as output_file:
    writer = csv.writer(output_file)
    writer.writerows(rows)