Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting file list using glob in python

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))
like image 743
liv2hak Avatar asked Nov 17 '15 02:11

liv2hak


Video Answer


2 Answers

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))
like image 100
Green Cell Avatar answered Sep 20 '22 04:09

Green Cell


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))
like image 29
Remi Crystal Avatar answered Sep 20 '22 04:09

Remi Crystal