python - 在 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]))
解决方案
您需要将距离转换为整数,然后才能根据值 10 进行检查:
而不是比较两个字符串:
if row[3]<='10':
你需要比较两个整数:
if int(row[3])<=10:
推荐阅读
- python - 带有 PostgreSQL 的 Plpython3u:与服务器的连接已丢失
- javascript - 如何为具有多种功能的按钮添加冷却效果?
- php - PHP MYSQL 类似文件
- python - 无法安装 Kivy(Windows 10、python 3.8)
- python - 更新 Anaconda-Navigator 环境后不起作用
- markdown - 在美人鱼序列图中添加盒子/容器
- android - Flutter Swiper,从另一个屏幕弹出后在同一页面上
- android - 如何使用数据绑定设置 Searchview
- angular - 为什么有些 CSS 类不能在组件样式中被覆盖,而另一些可以?
- composer-php - 安装 composer 没有可用的包 php-cli