Find all CSV files in a directory using Python Find all CSV files in a directory using Python python python

Find all CSV files in a directory using Python


import osimport globpath = 'c:\\'extension = 'csv'os.chdir(path)result = glob.glob('*.{}'.format(extension))print(result)


from os import listdirdef find_csv_filenames( path_to_dir, suffix=".csv" ):    filenames = listdir(path_to_dir)    return [ filename for filename in filenames if filename.endswith( suffix ) ]

The function find_csv_filenames() returns a list of filenames as strings, that reside in the directory path_to_dir with the given suffix (by default, ".csv").

Addendum

How to print the filenames:

filenames = find_csv_filenames("my/directory")for name in filenames:  print name


By using the combination of filters and lambda, you can easily filter out csv files in given folder.

import osall_files = os.listdir("/path-to-dir")    csv_files = list(filter(lambda f: f.endswith('.csv'), files))# lambda returns True if filename name ends with .csv or else False# and filter function uses the returned boolean value to filter .csv files from list files.