我有一个包含三列和多行的.csv文件,其中第一列是名称,第二列和第三列是值。我想过滤掉任何值小于1的行。因此,如果row[1] and row[2]
中的值为>=1
,我会编写一个脚本来读取文件并写入新文件。但是,我的输出文件包含输入文件中的所有内容,包括0的行。我无法弄清楚出了什么问题。非常感谢任何帮助!
from sys import argv
script, filename, outputfile = argv
import csv
#with open(filename,'r'), open (outputfile,'w') as fin, fout:
with open(filename,'r') as fin, open (outputfile,'w') as fout:
writer = csv.writer(fout, delimiter=',')
for row in csv.reader(fin, delimiter=','):
#if row[1] and row[2] >= 1:
if row[1] >=1 and row[2] >= 1:
writer.writerow(row)
答案 0 :(得分:1)
将字符串转换为int:
import csv
with open(filename,'r') as fin, open (outputfile,'w') as fout:
writer = csv.writer(fout, delimiter=',')
for row in csv.reader(fin, delimiter=','):
if int(row[1]) >=1 and int(row[2]) >= 1:
writer.writerow(row)