简体   繁体   English

python将列表写入csv

[英]python write list to csv

I have this code for trying to write list (of lists) to a csv, where each item (which is a list) should be written as a new csv row: 我有这段代码,试图将列表(列表)写到一个csv中,其中每个项目(一个列表)都应写为一个新的csv行:

    resultFile = open("E:/tmobile/CR_Accuracy/cycle7/pp/output.csv",'wb')
    wr = csv.writer(resultFile, dialect='excel')
    for item in result:
      wr.writerow([item,])

For some weird reason the csv file is empty after code executes and finishes. 由于某些奇怪的原因,在代码执行并完成后,csv文件为空。 An example to few of the list item copies from a 'Watch' with PyCharm: 带有PyCharm的“监视”中的几个列表项副本的示例:

    (7031482579417L, 'Payment', 'Yes', 'Yes - Both')
    (7031482579417L, 'Rate Plan OR Plan Fit Analysis', 'Yes', 'Yes - System')
    (7031482579417L, 'Credits and Adjustments', 'Yes', 'Yes - Both')

If the list is a list of tuples, just pass item , not item inside a list. 如果列表是元组列表,则只需传递item ,而不是列表中的item In addition to that, as theharshes comment, make sure that you closed the file. 除此之外,作为哈希注释,请确保关闭文件。

with open("E:/tmobile/CR_Accuracy/cycle7/pp/output.csv",'wb') as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    for item in result:
        wr.writerow(item)

or more shortly with csvwriter.writerows : 或更短时间内使用csvwriter.writerows

with open("E:/tmobile/CR_Accuracy/cycle7/pp/output.csv",'wb') as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    wr.writerows(result)

The code which you have given doesn't appear to close the file. 您提供的代码似乎没有关闭文件。 It may be that python never got around to flushing the file before the program ends. 可能是python在程序结束之前从来没有绕过刷新文件的过程。 If that is the case calling resultFlie.close() should fix it. 如果是这种情况,则调用resultFlie.close()应该对其进行修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM