Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through all CSV files in a folder

Tags:

python

I'm trying to loop through only the csv files in a folder that contains many kinds of files and many folders, I just want it to list all of the .csv files in this folder.

Here's what I mean:

import os, sys  path = "path/to/dir" dirs = os.listdir(path)  for file in dirs:     if file == '*.csv':         print file 

I know there is no wildcard variable in python, but is there a way of doing this?

like image 955
Sam Creamer Avatar asked Jan 10 '13 16:01

Sam Creamer


People also ask

How do I loop multiple files in a directory in Python?

Import the os library and pass the directory in the os. listdir() function. Create a tuple having the extensions that you want to fetch. Through a loop iterate over all the files in the directory and print the file having a particular extension.


1 Answers

Use the glob module: http://docs.python.org/2/library/glob.html

import glob path = "path/to/dir/*.csv" for fname in glob.glob(path):     print(fname) 
like image 164
Dan Hooper Avatar answered Sep 21 '22 22:09

Dan Hooper