11

I have a list of csv files in mydir.I want to get the list of file names. however using glob as below is returning an empty list.

import glob

mydir = "C:\Data"

file_list = glob(mydir + "*.csv")
print('file_list {}'.format(file_list))
1
  • 1
    Try glob.glob(mydir + "\*.csv") Commented Nov 17, 2015 at 2:15

3 Answers 3

12

Looks like you just need to include your slash to search in the correct directory.

import glob

mydir = "C:\Data"

file_list = glob.glob(mydir + "/*.csv") # Include slash or it will search in the wrong directory!!
print('file_list {}'.format(file_list))
Sign up to request clarification or add additional context in comments.

Comments

4

Try fnmatch:

import os
from fnmatch import fnmatch

mydir = "C:/Data"
file_list = [file for file in os.listdir(mydir) if fnmatch(file, '*.csv')]

print('file_list {}'.format(file_list))

Also, use RegEx:

import os
import re

mydir = "C:/Data"
file_list = [file for file in os.listdir(mydir) if re.search('.*\.png', file)]  

print('file_list {}'.format(file_list))

By the way, glob is a module, you should use glob.glob() like this:

from glob import glob

mydir = "C:/Data"

file_list = glob(mydir + "/*.csv")
print('file_list {}'.format(file_list))

Comments

1

You are missing a backslash between the filename and the directory. BUT you can't end a string with a single backslash, because it will think you are trying to escape the endquote. You can put it in the call to glob instead. (Note, that you'll want to make both strings raw, it's good practice in case your directory starts with an "n" or a "t", which in this case is interpreted as spacing characters.):

import glob
mydir = r"C:\Data"
file_list = glob.glob(mydir + r"\*.csv")
print('file_list {}'.format(file_list))

Also you might want to try using pylint to check for common errors or warnings. It would have thrown a warning for the unescaped directory name.

Update:

In fact I would just simplify it to this:

import glob
file_list = glob.glob(r"C:\Data\*.csv")
print('file_list {}'.format(file_list))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.