【发布时间】:2014-03-17 23:59:06
【问题描述】:
我有一堆文件名为
公司名称-日期_somenumber.txt
我必须根据公司名称对文件进行排序,然后根据日期对文件进行排序,并将其内容按此排序顺序复制到另一个文本文件中。
这是我正在尝试的方法:
从每个文件名中,提取公司名称和日期,将这两个字段放入字典中,将该字典附加到一个列表中,然后根据公司名称和日期这两列对这个列表进行排序。
然后一旦我有了排序顺序,我想我可以根据我刚刚获得的文件顺序搜索文件夹中的文件,然后将每个文件内容复制到一个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 的输出,我想我有我的字典列表。现在,我如何按公司名称然后按日期排序?我在网上查找了按多个键排序,但我如何获得按日期递增的顺序?
有没有其他方法可以按字符串和日期字段对列表进行排序?
【问题讨论】:
-
哈哈,这就是
YY-MM-DD的日期格式非常有用的原因。您的文件已经按正确的顺序排列了。 -
你是对的。我会尝试以这种方式重命名它们。谢谢
标签: python sorting dictionary text-files