赞
踩
What I'm trying to do is read into a csv document and find all values in the SN column > 20 and make a new file with only the rows with SN > 20.
I know that I need to do:
Read the original File
Open a new file
Iterate over rows of the original file
What I've been able to do is find the rows that have a value of SN > 20
import csv
import os
os.chdir("C:\Users\Robert\Documents\qwe")
with open("gdweights_feh_robert_cmr.csv",'rb') as f:
reader = csv.reader(f, delimiter= ',')
zerovar = 0
for row in reader:
if zerovar==0:
zerovar = zerovar + 1
else:
sn = row [11]
zerovar = zerovar + 1
x = float(sn)
if x > 20:
print x
So my question is how do I take the rows with SN > 20 and turn it into a new file?
解决方案
Save the data in a list, then write the list to a file.
import csv
import os
os.chdir(r"C:\Users\Robert\Documents\qwe")
output_ary = []
with open("gdweights_feh_robert_cmr.csv",'rb') as f:
reader = csv.reader(f, delimiter= ',')
zerovar = 0
for row in reader:
if zerovar==0:
zerovar = zerovar + 1
else:
sn = row [11]
zerovar = zerovar + 1
x = float(sn)
if x > 20:
print x
output_ary.append(row)
with open("output.csv",'w') as f2:
for row in output_ary:
for item in row:
f2.write(item + ",")
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。