CSV输出到文件Python 3

时间:2018-06-06 12:48:20

标签: python-3.x csv

我尝试从我通过的列表中将某些值打印到CSV中。这是我的功能:

current = datetime.datetime.now() #defining datetime for use in function
def write_csv(custody_parts):
    with open((current.strftime("%m_%d_%y_%H_%M_%S")) + '.csv', 'w', newline='') as csvfile:
         csvfile = io.StringIO()
         fieldnames = ['serial', 'user', 'time']
         writer = csv.DictWriter(csvfile, extrasaction='ignore', fieldnames=fieldnames)
         writer.writeheader()
         writer.writerows(custody_parts)
         csvfile.getvalue()
         print(csvfile.getvalue())
         return(csvfile.getvalue())```

然后我用我试图通过的列表调用它:

write_csv(parts)

并创建文件:06_06_18_12_13_53.csv

并打印到屏幕:

  

串行,用户,时间

     

SERIAL1,用户1,DATE1

     

serial2,用户2,DATE2

     

serial3,用户3,DATE3

但它创建的文件是empty,因此它不会写入正在创建的文件。

有人能指出我正确的方向吗?

谢谢〜

编辑:

我最终选择了这个:

def write_csv(custody_parts):
current = datetime.datetime.now()
    with open((current.strftime("%m_%d_%y_%H_%M_%S")) + '.csv', 'w', newline='') as csvfile:
        custodywriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
         custodywriter.writerow(['serial', 'user', 'time'])
         for i in custody_parts:
             x = [i["serial"],i["user"],i["time"]]
             custodywriter.writerow(x)
         custodywriter.writerow(["End of Report"])

0 个答案:

没有答案