在Python中,如何从目录中导入比我的SQL表中的日期更新的文件

在Python中,如何从目录中导入比我的SQL表中的日期更新的文件,python,csv,Python,Csv,我有一个包含许多原始数据.csv文件的文件夹,我为这些文件编写了一个脚本,用于导入、处理然后附加到SQL数据库表中 每天都会使用前一天的原始csv更新文件夹。我试图编写代码来搜索SQL数据库中的最新日期,并且只导入新的原始文件 Csv文件始终以DDMMYYYY_raw.Csv结尾 到目前为止,我已经: #Finding the max date in the SQL server maxdate = engine.execute("Select MAX([TableDate]) as 'Max

我有一个包含许多原始数据.csv文件的文件夹,我为这些文件编写了一个脚本,用于导入、处理然后附加到SQL数据库表中

每天都会使用前一天的原始csv更新文件夹。我试图编写代码来搜索SQL数据库中的最新日期,并且只导入新的原始文件

Csv文件始终以DDMMYYYY_raw.Csv结尾

到目前为止,我已经:

#Finding the max date in the SQL server
maxdate = engine.execute("Select MAX([TableDate]) as 'Max Date' From [dbo].[SQLTable]")
for row in maxdate:
    latestdate = row[0]
    print(latestdate)

#Adding 1 day so it gets the next days data csv
date2get = latestdate + timedelta(days=1)
print(date2get)

#Working out what year, month and day to get for 
yrtoget = date2get.year
mthtoget = date2get.month
daytoget = date2get.day

#Todays Date Calclulation
timerightnow = datetime.now()
yearend = timerightnow.year
monthend = timerightnow.month
dayend = timerightnow.day

#Start and end date
start_dt = date(yrtoget, mthtoget, daytoget)
end_dt = date(yearend, monthend, dayend)

#Date Calculation
def daterange(date1, date2):
    for n in range(int((date2 - date1).days) + 1):
        yield date1 + timedelta(n)

#Create and populate list of files to get
filestoget = []
for dt in daterange(start_dt, end_dt):
    filestoget.append(dt.strftime("%d%m%Y") + '_raw.csv')
print(filestoget)
因此,文件集给了我:

print(filestoget):

['06052020_raw.csv', '07052020_raw.csv']
这是正确的

问题:现在如何导入所有具有这些结尾的CSV

这是我目前必须导入的所有csv文件,但不是针对特定日期

csvfiles = glob.glob(os.path.join(file_path, '*.csv'))
for csvfile in csvfiles:
    with open(csvfile, 'r') as read_obj:
    ...#code then starts
    ...
    ...
我需要创建另一个循环吗?并调整csvfiles=glob.globos.path.joinfile_path,'*.csv'行

任何帮助都将不胜感激。谢谢诸如此类的东西:

endings  = ['06052020_raw.csv', '07052020_raw.csv']
csvfiles = glob.glob(os.path.join(file_path, '*.csv'))
for csvfile in csvfiles:
    if any(csvfile.endswith(ending) for ending in endings):
        with open(csvfile, 'r') as read_obj:
        ...#code then starts

我最终得到了它。比我想象的要简单,我只需要添加另一个循环,并将下面的所有代码转换为行:

for files in filestoget:
    csvfiles = glob.glob(os.path.join(file_path, '*'+ files))
    for csvfile in csvfiles:
        # open file in read mode
        with open(csvfile, 'r') as read_obj:
        ...#code then starts

谢谢@Bobby Ocean。我我基本上只是想找到文件夹中包含['06052020_raw.csv'、'07052020_raw.csv']的所有文件。我会更新问题谢谢你,博比·奥森。我还找到了一个解决方案,但只需在filestogetAdding上添加一个额外的循环就意味着您将搜索lenfilestoget*lencsvfiles目录,这比执行一个循环要多得多的搜索和计算。小心点。谢谢@Bobby Ocean。我没有意识到这一点,所以知道这一点很好。非常感谢,您的解决方案成功了,这确实是一个操作系统问题,您要求操作系统多次读取同一目录,这在非常大的数据集或大量文件上可能会很慢。