0

In a directory i have multiple files. but i want to fetch only few csv files with particular pattern.

Example

files in a directory: abc.csv, xyz.csv, uvw.csv, sampl.csv, code.py, commands.txt, abc_1.csv, sam.csv, xyz_1.csv, uvw_1.csv, mul.csv, pp.csv......

I need to fetch csv filenames : abc.csv , xyz.csv, uvw.csv, abc_1.csv, xyz_1.csv, uvw_1.csv, abc_2.csv , xyz_2.csv, uvw_2.csv,.... (sometimes more files with change in just the number in filename like abc_3.csv)

In python we can fetch the files using

files = glob.glob("*.csv")

But for the above requirement how to modify the above line or any other efficient way of doing it

sweety
  • 111
  • 1
  • 2
  • 10

1 Answers1

0

Using Regex.

Ex:

import glob
import os
import re

for filename in glob.glob(r"Path\*.csv"):
    if re.match(r"[a-z]{3}(_\d*)?\.csv", os.path.basename(filename)):
        print(filename)
Rakesh
  • 81,458
  • 17
  • 76
  • 113