【发布时间】: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 > 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.csv 和 output2.csv 都可以在 Excel 中打开,这一点很重要。
【问题讨论】:
标签: python python-3.x