【问题标题】:Write String and integer to CSV file将字符串和整数写入 CSV 文件
【发布时间】:2017-05-22 23:25:55
【问题描述】:

我有一个代码,其输出如下所述。

  print "Total Bits:%d"%totalbits
  print "Number of totalbits-zeros: %d." %totalbitszeros
  print "Number of totalbits-ones: %d." %totalbitsones
  print "Number of BRAM-Zeros: %d." %count0_bram
  print "Number of BRAM-ones: %d." %count1_bram
  print "Number of NON_BRAM-Zeros: %d." %count0_nonbram
  print "Number of NON_BRAM-Ones: %d." %count1_nonbram
  print "difference_zero_non_BRAM:%d."%difference_zero_non_BRAM
  print "difference_ones_non_BRAM:%d."%difference_ones_non_BRAM

为此,我想将这些数据写入 .csv 文件:我创建了一个数组,如:data=[['Total Bits',totalbits]]

并编写此代码以将数据写入 .csv 文件。

for row in data:
   for col in row:
    out.write('%d;'%col))

   out.write('\n')
  out.close()

但它给了我一个错误,因为列中的第一个元素是一个字符串,有没有办法将此数据写入 .csv 文件,无论是否转换为数组。 .csv 文件中的输出看起来像第一列描述(字符串)和第二列数字(整数)。

Total bits                       77826496
Total number of bits@0:          74653999
Total number of bits@1:          3172497
Total number of BRAM  bits@0:    17242039
Total number of BRAM  bits@1:    62089
Total number of non-BRAM  bits@0: 57411960
Total number of non-BRAM  bits@:  3110408

【问题讨论】:

  • 使用csv 模块。

标签: python python-2.7 csv


【解决方案1】:

您可以使用格式化功能。像这样:

data = [['Total Bits', 100]]
with open('output.csv','w') as out:
    for row in data:
        for col in row:
            out.write('{0};'.format(col))
        out.write('\n')

【讨论】:

    【解决方案2】:

    您可以尝试使用 csv 模块:

    import csv
    a = [['Total bits',77826496],['Total number of bits@0',74653999],['Total number of bits@1',3172497],\
         ['Total number of BRAM  bits@0',17242039],['Total number of BRAM  bits@1',62089],\
         ['Total number of non-BRAM  bits@0', 57411960],['Total number of non-BRAM  bits@',3110408]]
    with open("output.csv", "wb") as f:
        writer = csv.writer(f,delimiter=':')
        writer.writerows(a)
    

    output.csv 文件将是:

    Total bits:77826496
    Total number of bits@0:74653999
    Total number of bits@1:3172497
    Total number of BRAM  bits@0:17242039
    Total number of BRAM  bits@1:62089
    Total number of non-BRAM  bits@0:57411960
    Total number of non-BRAM  bits@:3110408
    

    【讨论】:

      猜你喜欢
      • 2015-07-16
      • 2016-10-22
      • 1970-01-01
      • 2022-12-05
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多