Akash
Akash

Reputation: 59

Python : How to call csv files from the directory based on the list of items?

I have a list of items and I want to call only those csv files from the directory whose names are similar to the items in the list. I am doing something like below but its reading all the files from the directory. Please suggest.

x_list = [ a,b,c,d]
files in directory = [a.csv, b.csv, c.csv, d.csv, e.csv, f.csv]

for files in os.listdir(dir + 'folder\\'):
    file_name = files[:files.find('.')]
    if file_name in x_list:
        print(file_name) 

Upvotes: 1

Views: 98

Answers (3)

Laurent B.
Laurent B.

Reputation: 2263

From official doc : "The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order."

import glob
dirPath = "/home/.../"
pattern = dirPath + '*.csv'

for file_path in glob.glob(pattern):
    print(file_path)

Upvotes: 1

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15568

You can just open the CSVs on your list: This is what you could do:


# a b c d are names of CSVs without .csv extension
my_csvs_names =  'a b c d'.split()
my_csvs_folder = 'c/path/to/my_folder'

for csv_name in my_csvs_names:
    file_name = f'{my_csvs_folder}/{csv_name}.csv'
    try:
        with open(file_name, 'r') as f_in:
            for line in f_in:
                # do something with it
                print(line)

    except FileNotFoundError:
        print(f'{file_name} does not exist')

In doing something, you can append values to a variable or whatever you are trying to achieve.

Upvotes: 0

Amal K
Amal K

Reputation: 4874

You can use regular expressions for which you'll need the re module.

import re
print(*(file for file in os.listdir() if re.match(r".*\.csv", file) and file[:-4] in x), sep='\n') 

You can also use the filter function:

print(*filter(lambda file:  re.match(r".*\.csv", file) and file[:-4] in x, os.listdir(), sep='\n')

Upvotes: 0

Related Questions