Home > Mobile >  List all the csv files containing specific subtring
List all the csv files containing specific subtring

Time:03-19

I have 200 12MB CSV files and I have to search through all of them to list all the CSV containing a specific substring. Nevertheless, something is wrong with either loop or how I read the file because no results are printed and I have no idea how to fix it.

I have tried other stackoverflow solutions but none has worked, unfortunately.

import csv, os, glob
 
path = r'C:/Users/me/Desktop/csvfolder/*csv'
keyword = '261892'
 
for Tname in glob.glob(path):
    #print (os.path.abspath(Tname))
    #read csv, and split on "," the line
    csv_file = csv.reader(open(os.path.abspath(Tname), "r",encoding= 'UTF-8'), delimiter=",") 
    for row in csv_file:
        if keyword == row[0]:
              print (os.path.abspath(Tname))

           

CodePudding user response:

Did you check the type of 'csv_file' variable? If it became a list, I assume there won't be any rows or columns, but list of lists.

CodePudding user response:

You might what to check for blank rows by adding 'if row:' to your code:

    for row in csv_file:
        if row:
            if keyword == row[0]:
                  print (os.path.abspath(Tname))

I tested it with a set of 80 csv files of my own and got it to work.

  • Related