在python中按日期和字符串排序

2024-07-05 09:55:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一堆文件名为

公司名称日期_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列表了。现在,如何按公司名称和日期排序?我在网上查到了按多个键排序,但如何才能得到按日期递增的订单呢?在

有没有其他方法可以让我先按字符串再按日期字段排序?在


Tags: 文件intxt名称列表date排序公司
1条回答
网友
1楼 · 发布于 2024-07-05 09:55:12
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'))允许sorted按公司名称排序,然后按日期排序。在

相关问题 更多 >