【问题标题】:Python write to list to CSVPython 将列表写入 CSV
【发布时间】:2014-07-03 15:09:02
【问题描述】:

我的 CSV 写入语句无法正常工作;

我有一个包含字符串的列表,每个字符串都需要写入 csv 中自己的行;

mylist = ['this is the first line','this is the second line'........]
with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(mylist)

问题是,我的输出在某处搞砸了,看起来像这样;

't,h,i,s, i,s, t,h,e, f,i,r,s,t, l,i,n,e,'.... etc.

我需要;

'this is the first line'
'this is the second line'

【问题讨论】:

    标签: python list csv


    【解决方案1】:

    csvwriter.writerows 应该与序列的序列(或可迭代的)一起使用。 (mylist 也是一个序列序列,因为字符串可以看作是一个单字符串序列)

    对每个 mylist 项目使用 csvwriter.writerow

    mylist = ['this is the first line','this is the second line'........]
    with open("output.csv", "wb") as f:
        writer = csv.writer(f)
        for row in mylist:
            writer.writerow([row])
    

    要使用writerows,请将列表转换为序列序列:

    mylist = ['this is the first line','this is the second line'........]
    with open("output.csv", "wb") as f:
        writer = csv.writer(f)
        rows = [[row] for row in mylist]
        writer.writerows(rows)
    

    【讨论】:

      【解决方案2】:

      你必须像这样迭代列表项

        mylist = ['this is the first line','this is the second line']
        with open("output.csv", "wb") as f:
            writer = csv.writer(f)
            for item in mylist:
                writer.writerow([item])
      

      【讨论】:

        猜你喜欢
        • 2021-11-09
        • 1970-01-01
        • 2014-09-21
        • 2016-06-30
        • 1970-01-01
        • 2013-07-16
        • 2012-01-02
        • 1970-01-01
        相关资源
        最近更新 更多