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))
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With