首页 > 解决方案 > 在 Python 中的 csv 文件中使用 for 循环

问题描述

我在 Python 2.7 中运行了一段代码。我有三列 ID1、ID2 和 DISTANCE。我想要距离小于 10 米的所有行值。当我运行以下代码时,输​​出显示所有行。我希望 DISTANCE 小于 10 米。

import csv
# open and read the csv file into memory
file = open('C:\\Users\\ADMIN\\Desktop\\Data\\2 July\\ndata.csv')
reader = csv.reader(file)
# iterate through the lines and print them to stdout
# the csv module returns us a list of lists and we
# simply iterate through it

if __name__ == "__main__":
file=open("sourav.csv","w") ## open file in write mode
for row in reader:
     if row[3]<='10':

         print "({} {} {})".format(row[1], row[2], row[3])
         file.write("{} {} {}\n".format(row[1], row[2], row[3]))

标签: python

解决方案


您需要将距离转换为整数,然后才能根据值 10 进行检查:

而不是比较两个字符串:

if row[3]<='10':

你需要比较两个整数:

if int(row[3])<=10:

推荐阅读