[英]How to use the items of the list, with the glob.glob to get the files?
There are various csv files in the directory containing dates as name( somename_20210202.csv
, xyzname_20210305.csv
, etc.).在包含日期作为名称的目录中有各种 csv 文件( somename_20210202.csv
, xyzname_20210305.csv
,等)。 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.此外,我想在 glob.glob 中使用该模式来获取文件,但globbed_files
返回空列表。 My code is correct till pattern_list
.我的代码在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.您的模式是正确的,并且从 glob 模块获取文件也是正确的。 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. csv文件存在于您的文件目录( 'C:\User\Folder'
)路径中,然后您将从globbed_files
获得相同的结果,否则银行列表。
For example:例如:
Creates two or more file as a_20210202.csv, b_20210202.csv and c_20210305.csv
etc...创建两个或多个文件为a_20210202.csv, b_20210202.csv and c_20210305.csv
等...
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.注意:示例仅用于演示目的,其 static 方式创建文件然后获取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.