python对csv文件中某一列进行遍历_Python循环遍历CSV文件及其列

这篇博客讨论了使用Python3遍历CSV文件并处理特定列的问题。作者遇到索引错误,尝试打印第四列时出现“list index out of range”。解决方案指出Python计数从0开始,建议检查CSV文件的列数,并正确迭代每一行的每个单元格。

so I've seen this done is other questions asked here but I'm still a little confused. I've been learning python3 for the last few days and figured I'd start working on a project to really get my hands dirty. I need to loop through a certain amount of CSV files and make edits to those files. I'm having trouble with going to a specific column and also for loops in python in general. I'm used to the convention (int i = 0; i < expression; i++), but in python it's a little different. Here's my code so far and I'll explain where my issue is.

import os

import csv

pathName = os.getcwd()

numFiles = []

fileNames = os.listdir(pathName)

for fileNames in fileNames:

if fileNames.endswith(".csv"):

numFiles.append(fileNames)

for i in numFiles:

file = open(os.path.join(pathName, i), "rU")

reader = csv.reader(file, delimiter=',')

for column in reader:

print(column[4])

My issue falls on this line:

for column in reader:

print(column[4])

So in the Docs it says column is the variable and reader is what I'm looping through. But when I write 4 I get this error:

IndexError: list index out of range

What does this mean? If I write 0 instead of 4 it prints out all of the values in column 0 cell 0 of each CSV file. I basically need it to go through the first row of each CSV file and find a specific value and then go through that entire column. Thanks in advance!

解决方案

It could be that you don't have 5 columns in your .csv file.

Python is base0 which means it starts counting at 0 so the first column would be column[0], the second would be column[1].

Also you may want to change your

for column in reader:

to

for row in reader:

because reader iterates through the rows, not the columns to my understanding.

This code loops through each row and then each column in that row allowing you to view the contents of each cell.

for i in numFiles:

file = open(os.path.join(pathName, i), "rU")

reader = csv.reader(file, delimiter=',')

for row in reader:

for column in row:

print(column)

if column=="SPECIFIC VALUE":

#do stuff

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值