我有一堆文件名为
公司名称日期_somenumber.txt在
我必须根据公司名称对文件进行排序,然后再根据日期排序,并将其内容按此排序顺序复制到另一个文本文件中。在
我尝试的方法是:
从每个文件名中提取公司名称,然后提取日期,将这两个字段放入字典中,将此字典附加到列表中,然后根据companyname和date的两列对列表进行排序。在
然后,一旦我有了排序顺序,我想我可以根据我刚刚获得的文件顺序搜索文件夹中的文件,然后将每个文件的内容复制到一个txt文件中,我将得到最后的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的输出,我想我有我的dicts列表了。现在,如何按公司名称和日期排序?我在网上查到了按多个键排序,但如何才能得到按日期递增的订单呢?在
有没有其他方法可以让我先按字符串再按日期字段排序?在
函数
sorted
接受一个关键字参数key
,这是一个应用于排序序列中每个项目的函数。如果这个函数返回一个元组,序列将按元组中的项依次排序。在这里
lambda x: (x.get('company'),x.get('file_date'))
允许sorted
按公司名称排序,然后按日期排序。在相关问题 更多 >
编程相关推荐