python中按日期和字符串排序
我有一堆文件,文件名如下 companyname-date\u somenumber.txt 我必须根据公司名称对文件进行排序,然后根据日期对文件进行排序,然后按照排序的顺序将其内容复制到另一个文本文件中 以下是我正在尝试的方法: 从每个文件名中提取公司名称,然后提取日期,将这两个字段放入字典中,将此字典附加到列表中,然后根据companyname和date的两列对列表进行排序 然后,一旦我有了排序顺序,我想我可以根据我刚刚获得的文件顺序搜索文件夹中的文件,然后将每个文件内容复制到一个txt文件中,我将得到我的最终txt文件 以下是我目前掌握的代码:python中按日期和字符串排序,python,sorting,dictionary,text-files,Python,Sorting,Dictionary,Text Files,我有一堆文件,文件名如下 companyname-date\u somenumber.txt 我必须根据公司名称对文件进行排序,然后根据日期对文件进行排序,然后按照排序的顺序将其内容复制到另一个文本文件中 以下是我正在尝试的方法: 从每个文件名中提取公司名称,然后提取日期,将这两个字段放入字典中,将此字典附加到列表中,然后根据companyname和date的两列对列表进行排序 然后,一旦我有了排序顺序,我想我可以根据我刚刚获得的文件顺序搜索文件夹中的文件,然后将每个文件内容复制到一个txt文件
myfiles = [ f for f in listdir(path) if isfile(join(path,f)) ]
file_list=[]
for file1 in myfiles:
# find indices of companyname and date in the file-name
idx1=file1.index('-',0)
idx2=file1.index('_',idx1)
company=file1[0:idx1] # extract companyname
thisdate=file1[idx1+1:idx2] #extract date, which is in format MMDDYY
dict={}
# extract month, date and year from thisdate
m=thisdate[0:2]
d=thisdate[2:4]
y='20'+thisdate[4:6]
# convert into date object
mydate = date(int(y), int(m), int(d))
dict['date']=mydate
dict['company']=company
file_list.append(dict)
我在这段代码的末尾检查了file_list的输出,我想我有我的dict列表。现在,我如何按公司名称排序,然后按日期排序?我在网上查到了按多个键排序的方法,但是我怎样才能得到按日期递增的顺序呢
有没有其他方法可以按字符串和日期字段对列表进行排序
import os
from datetime import datetime
MY_DIR = 'somedirectory'
# my_files = [ f for f in os.listdir(MY_DIR) if os.path.isfile(os.path.join(MY_DIR,f)) ]
my_files = [
'ABC-031814_01.txt',
'ABC-031214_02.txt',
'DEF-010114_03.txt'
]
file_list = []
for file_name in my_files:
company,_,rhs = file_name.partition('-')
datestr,_,rhs = rhs.partition('_')
file_date = datetime.strptime(datestr,'%m%d%y')
file_list.append(dict(file_date=file_date,file_name=file_name,company=company))
for row in sorted(file_list,key=lambda x: (x.get('company'),x.get('file_date'))):
print row
函数sorted
接受一个关键字参数key
,它是应用于排序序列中每个项的函数。如果此函数返回一个元组,则序列将依次按元组中的项进行排序
这里
lambda x:(x.get('company'),x.get('file_date'))
允许排序
按公司名称排序,然后按日期排序。Hah,这就是为什么YY-MM-DD
的日期格式非常有用的原因。你的文件已经按正确的顺序排列了,你是对的。我将尝试用这种方式重命名它们。谢谢