Python Looping through CSV Files and Their Columns

so I saw that it was done, these are other questions asked here, but I'm still a little confused. I have been studying python3 in the last few days and thought that I would start working on a project to spoil my hands. I need to scroll through a certain number of CSV files and make changes to these files. I'm having trouble visiting a specific column, as well as for loops in python in general. I'm used to convention (int i = 0; i <expression; i ++), but in python this is a little different. Here is my code so far, and I will explain where my problem 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 problem relates to this line:

for column in reader:
        print(column[4])

So, in the Docs, it says that the column is a variable, and the reader is what I am viewing. But when I write 4, I get this error:

IndexError: list index out of range

? 0 4, 0 0 CSV. , CSV , . !

+4
2

, 5 CSV .

Python - base0, , 0, [0], - [1].

for column in reader:

for row in reader:

, , .

, .

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
+2

Python! .

:

for row in reader:
    try:
        print(row[4])
    except IndexError as ex:
        print("ERROR: %s in file %s doesn't contain 5 colums" % (row, i))

( , CSVReader), CSV.

:

  • snake_case Python, camelCase
  • (csv_filename i, row column ..)
  • with ( )

!

+3

Source: https://habr.com/ru/post/1684702/


All Articles