dimanche 7 février 2021

How to select rows in a csv file beased on the lenght?

I'm trying to select the rows based on their length. Some of the rows in my csv file have 5 items, some have 20 items and some have 40. I want to collect all the rows if their lenght is between 24 and 34. So I tried below code:

my_path = r'c:\data\FF\Desktop\my_files' 

for file in os.listdir(my_path):
    path_file = os.path.join(my_path, file)
    with open(path_file, 'r') as output:
        reader = csv.reader(output, delimiter = ',')
        read = [row for row in reader if row] 
        for row in read:
            if len(row) > 24 or len(row) < 34:
                if row[9] == '3080':
                    print(row[0] + ',' + row[24] + ',' + row[25] + ',' 
                          + row[26] + ',' + row[27] + ',' + row[28] + ',' + row[29]
                          + ',' + row[30] + ',' + row[31] + ',' + row[32] + ',' + row[33] + ','
                          + row[34])

I receive the following error:

  File "C:\data\FF\Desktop\Python\PythongMySQL\untitled2.py", line 15, in <module>
    if row[9] == '3080':

IndexError: list index out of range

I expect to get several rows with a lenght between 24 and 34.

Aucun commentaire:

Enregistrer un commentaire