我意识到这个问题已被问及一百万次,并有大量的文件。但是,我无法以正确的格式输出结果。写输出到CSV文件[以正确的格式]
下面的代码获得通过从: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中打开。
感谢。那样做了!所以你只需要添加新行('/ n')! 1)的作品。 2)仍然没有,但没关系。 – Novice
请注意,我很惊讶1)的工作,因为在Unix上'\ n'会转换为LF,而我非常确定Excel只会在CRLF结束时接受csv文件。实际上,这是CSV格式的一个特性,单个LF表示单元格内的换行符。这就是为什么你打开Python 2的'rb'和Python 3的'newline =''的原因,因为csv编写器处理这个特定的方面,并且会被Python的默认换行抽象打扰。 – Cilyan