我对 Python 很陌生。
基本问题:从目录中提取按年、月和日排序的文件名列表
我正在编写一个搜索最新 bak 的脚本
目录中的文件并将其导入数据库。
文件具有以下格式:
MyDB_05-09-2017.bak
MyDB_05-10-2017.bak
我希望通过文件名提取最新的 bak 文件。
我想按年、月和日对文件进行排序。
这是我尝试过的一些基本实现:
import glob,os,re
from datetime import datetime
# SQL server backup directory
os.chdir('C:\\SQLServerBackups')
# invoke the sql script to drop the database if exists
os.system('C:\\SQLServerBackups\\database_sql_scripts\\drop_database.bat')
# find the latest .bak file and rename it to target
file_list = glob.glob('*.bak')
latest_bak_file = file_list[0]
latest_year = 0
latest_month = 0
latest_day = 0
for file in file_list:
print(file)
del_list = re.split('[-._]',file)
temp_latest_year = int(del_list[3])
temp_latest_month = int(del_list[1])
temp_latest_day = int(del_list[2])
if temp_latest_year > latest_year:
latest_year = temp_latest_year
latest_month = temp_latest_month
latest_day = temp_latest_day
elif temp_latest_year == latest_year:
if temp_latest_month > latest_month:
latest_month = temp_latest_month
latest_day = temp_latest_day
elif temp_latest_month == latest_month:
if temp_latest_day > latest_day:
latest_day = temp_latest_day
latest_bak_file = file
print(latest_bak_file)
关于如何更好地实施它的任何建议?
我希望有一个按年、月和日排序的文件名列表。
您可以定义一个排序键函数,该函数返回您想要排序的字段:
import re
fnames = [
"MyDB_05-10-2017.bak",
"MyDB_05-09-2017.bak",
]
def sortkey(x):
parts = re.split('[-._]', x)
return [int(parts[3]), int(parts[1]), int(parts[2])]
sorted_fnames = sorted(fnames, key=sortkey)
或者,正如@Klaus D 所说,datetime.strptime
在您的搜索键中使用:
sorted_fnames = sorted(fnames, key=lambda x: datetime.datetime.strptime(x, 'MyDB_%d-%m-%Y.bak'))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句