0

我在重写 CSV 文件时遇到问题。我所拥有的是一个包含 20 列的 CSV 文件,我将其重写为只有 5 列。现在,我需要删除一些不必要的点,其中 SN < 20。它有效,唯一的问题是它没有将行。它将所有内容都放在第 1 行。我猜它来自,

output_ary.append(row) 

但我不知道那里还能写什么。这是代码的一部分:

import csv
import os
import matplotlib.pyplot as plt

os.chdir("C:\Users\Robert\Documents\qwe")

r = csv.reader(open("gdweights_feh_robert_cmr.csv",'rU'))

w = csv.writer(open("gdweight.csv",'wb',buffering=0))

zerovar2 = 0
for row in r:
        if zerovar2==0:
        zerovar2 = zerovar2 + 1
    else:
                sn = float(row[11])
                rweight = float(row[17])
                tarweight = float(row[18])
                fehadop = float(row[25])
                weight = rweight*tarweight*fehadop
                w.writerow([sn,rweight,tarweight,fehadop,weight])



output_ary = []

with open("gdweight.csv",'rU') as f:
    reader = csv.reader(f, delimiter= ',')
    zerovar = 0
    for row in reader:
        if zerovar==0:
                zerovar = zerovar + 1
        else:
                sn = row [0]
                zerovar = zerovar + 1
                x = float(sn)
                if x > 20:
                    output_ary.append(row)

with open("ouput1.csv",'w') as f2:
    for row in output_ary:
        for item in row:
            f2.write(item + ",")
4

2 回答 2

1
with open("ouput1.csv",'w') as f2:
    for row in output_ary:
        for item in row:
            f2.write(item + ",")
        f2.write("\n") # this is what you're missing
于 2013-04-18T20:02:47.473 回答
0

简单地将最后一个重写为:

with open("ouput1.csv",'w') as f2:
    for row in output_ary:
        f2.write(",".join([str(e) for e in item] + '\n')

现在这里有一些额外的评论:

您可以使用 enumerate 而不是使用计数器:

for i_row, row in enumerate(r) :
    ...

您还可以使用 csv 编写器:

with open("output.txt", "w") as f :
    csv_w = csv.writer(f)
    for i_row, row in enumerate(output) : 
        if i_row== 0 :
            continue
        csv_w.writerow(row)
于 2013-04-18T20:03:07.057 回答