There are various csv files in the directory containing dates as name( somename_20210202.csv
, xyzname_20210305.csv
, etc.). I would like to read the files for the given date range mentioned below. With the list of those dates, I created a pattern of files. Further, I want to use that pattern in glob.glob to get files but globbed_files
returning empty list. My code is correct till pattern_list
. Please suggest where is the problem.
from datetime import timedelta, date
import pandas as pd
import numpy as np
import glob
import os
import datetime as dt
def daterange(date1, date2):
for n in range(int ((date2 - date1).days)+1):
yield date1 + timedelta(n)
start_dt = date(2020,01,15)
end_dt = date(2020,02,10)
abc = []
weekdays = [5,6]
for dt in daterange(start_dt, end_dt):
if dt.weekday() not in weekdays:
abc.append(dt.strftime("%d-%b-%Y"))
#print(dt.strftime("%d-%b-%Y"))
print(abc)
dir = r"C:\User\Folder"
pattern_list = []
for dates in abc:
pattern = f'*_{dates}.csv' # use wildcards (*)
pattern_list.append(pattern)
print(pattern_list)
for x in pattern_list:
globbed_files = glob.glob(os.path.join(dir, x))
print(globbed_files)
Your pattern is correct and also get files from the glob module is correct. Only make sure your . csv file exists in your file directory( 'C:\User\Folder'
) path and then you will get the same result from globbed_files
otherwise bank list.
For example:
Creates two or more file as a_20210202.csv, b_20210202.csv and c_20210305.csv
etc...
and set your pattern date list as well like:
pattern_list = [*_20210202.csv, *_20210305.csv]
then:
dir = "your created files folder path"
for x in pattern_list:
globbed_files = glob.glob(os.path.join(dir, x))
print(globbed_files)
Note : example only demo purpose only, its static way to creates file and then get.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.