在我的python应用程序中,我需要将一些值导出为csv。但是问题是我需要为其添加一些值。我尝试了以下解决方案:
import csv
from datetime import datetime
from collections import deque
def writeCSV(path,participants,values):
time=datetime.now()
with open(path, 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
for value in values:
if type(value) is list:
value.prepend(participants)
value.prepend(time)
writer.writerow(value)
else:
writer.writerow([time,participants,value])
if __name__ == '__main__':
writeCSV('demo.csv',15,[['hentai','ecchi'],['power','ranger']])
但是我收到以下错误:
Traceback (most recent call last):
File "csv_deque.py", line 21, in <module>
writeCSV('demo.csv',15,[['hentai','ecchi'],['power','ranger']])
File "csv_deque.py", line 13, in writeCSV
value.prepend(participants)
我该如何解决。
答案 0 :(得分:0)
问题在于列表没有prepend
方法。 (但是如果有的话会很好)
因此,就我而言,我遇到了类似的问题:我需要在csv文件的每个条目之前添加一些参与者和日期时间。
因此,就像我在本例中所做的那样,我建议您将脚本变成这样:
import csv
from datetime import datetime
from collections import deque
def writeCSV(path,participants,values):
time=datetime.now()
with open(path, 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
for value in values:
if type(value) is list:
value=deque(value)
value.appendleft(participants)
value.appendleft(time)
writer.writerow(value)
else:
writer.writerow([time,participants,value])
if __name__ == '__main__':
writeCSV('demo.csv',15,[['hentai','ecchi'],['power','ranger']])
如您所见,我使用dequeue
,如本answer所示。您还可以看到也可以将dequeue
对象写为csv。