Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all CSV files in a directory using Python

How can I find all files in directory with the extension .csv in python?

like image 702
mintgreen Avatar asked Feb 10 '12 20:02

mintgreen


People also ask

How do I search all files in a directory in Python?

Use isfile() function path. isfile('path') function to check whether the current path is a file or directory. If it is a file, then add it to a list. This function returns True if a given path is a file.


3 Answers

import os
import glob

path = 'c:\\'
extension = 'csv'
os.chdir(path)
result = glob.glob('*.{}'.format(extension))
print(result)
like image 119
thclpr Avatar answered Oct 17 '22 22:10

thclpr


from os import listdir

def 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
like image 59
Bernhard Kausler Avatar answered Oct 17 '22 20:10

Bernhard Kausler


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

import os

all_files = os.listdir("/path-to-dir")    
csv_files = list(filter(lambda f: f.endswith('.csv'), all_files))

# lambda returns True if filename (within `all_files`) ends with .csv or else False
# and filter function uses the returned boolean value to filter .csv files from list files.
like image 28
Thejesh PR Avatar answered Oct 17 '22 22:10

Thejesh PR