【问题标题】:Writing output to csv file [in correct format]将输出写入 csv 文件 [以正确的格式]
【发布时间】:2015-11-12 01:50:11
【问题描述】:

我知道这个问题已经被问了一百万次,并且有很多关于它的文档。但是,我无法以正确的格式输出结果。

以下代码来自:Replacing empty csv column values with a zero

# Save below script as RepEmptyCells.py 
# Add #!/usr/bin/python to script 
# Make executable by chmod +x prior to running the script on desired .csv file 

# Below code will look through your .csv file and replace empty spaces with 0s
# This can be particularly useful for genetic distance matrices 

import csv
import sys

reader = csv.reader(open(sys.argv[1], "rb"))
for row in reader:
    for i, x in enumerate(row):
                if len(x)< 1:
                         x = row[i] = 0
    print(','.join(int(x) for x in row))

目前,要获得正确的输出 .csv 文件 [即格式正确] 可以在 bash 中运行以下命令:

 #After making the script executable        
./RepEmptyCells.py input.csv > output.csv # this produces the correct output 

我尝试使用csv.writer 函数生成格式正确的output.csv 文件(类似于./RepEmptyCells.py input.csv &gt; output.csv),但运气不佳。

我想了解如何将这最后一部分添加到代码中以自动执行该过程,而无需在 bash 中执行此操作。

我尝试过的:

f = open(output2.csv, 'w') 

import csv
import sys

reader = csv.reader(open(sys.argv[1], "rb"))
for row in reader:
    for i, x in enumerate(row):
                if len(x)< 1:
                         x = row[i] = 0
    f.write(','.join(int(x) for x in row)) 

f.close() 

查看这段代码和之前的原始文件时,它们看起来是一样的。

但是,当我在 excel 或 iNumbers 中打开它们时,后者(即output2.csv)仅显示一行数据。

output.csvoutput2.csv 都可以在 Excel 中打开,这一点很重要。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    2 个选项:

    1. 只需在您当前的 f.write 声明之后执行 f.write('\n')

    2. 使用csv.writer。您提到它,但它不在您的代码中。

      writer = csv.writer(f)
      ...
      writer.writerow([int(x) for x in row])  # Note difference in parameter format
      

    【讨论】:

    • 谢谢。做到了!所以你只需要添加新行('/n')! 1)作品。 2) 仍然没有,但没关系。
    • 当心,我很惊讶 1) 工作,因为在 Unix 上 '\n' 将转换为 LF,而我很确定 Excel 只会接受以 CRLF 结尾的 csv 文件。实际上,这是 CSV 格式的一个特点,单个 LF 表示单元格内的换行符。这就是为什么您将文件打开为 Python 2 的 'rb' 和 Python 3 的 newline='' 的原因,因为 csv 编写器会处理这个特定方面,并且会被 Python 的默认换行符抽象干扰。
    【解决方案2】:

    一个不起眼的提议

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import csv
    import sys
    
    # Use with statement to properly close files
    # Use newline='' which is the right option for Python 3.x
    with open(sys.argv[1], 'r', newline='') as fin, open(sys.argv[2], 'w', newline='') as fout:
        reader = csv.reader(fin)
        # You may need to redefine the dialect for some version of Excel that 
        # split cells on semicolons (for _Comma_ Separated Values, yes...)
        writer = csv.writer(fout, dialect="excel")
        for row in reader:
            # Write as reading, let the OS do the caching alone
            # Process the data as it comes in a generator, checking all cells
            # in a row. If cell is empty, the or will return "0"
            # Keep strings all the time: if it's not an int it would fail
            # Converting to int will force the writer to convert it back to str
            # anwway, and Excel doesn't make any difference when loading.
            writer.writerow( cell or "0" for cell in row )
    

    示例in.csv

    1,2,3,,4,5,6,
    7,,8,,9,,10
    

    输出out.csv

    1,2,3,0,4,5,6,0
    7,0,8,0,9,0,10
    

    【讨论】:

      【解决方案3】:
      import csv
      import sys
      
      with open(sys.argv[1], 'rb') as f:
          reader = csv.reader(f)
          for row in reader:
              print row.replace(' ', '0')
      

      我不明白您需要使用 shell 和重定向。 一个 csv 作家只是:

      with open('output.csv', 'wb') as f:
          writer = csv.writer(f)
          writer.writerows(rows)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-03
        • 1970-01-01
        • 1970-01-01
        • 2011-07-27
        • 1970-01-01
        • 2015-07-08
        • 1970-01-01
        相关资源
        最近更新 更多