Issue
I trying to sort the date inside my list, but the dates comes after a string element [EQUIP-X]
. First using regex, take the only date and tried to sort. It doesn't work!
I thought to split the string [EQUIP-X]
and Date
.
files = [filename for root, dirs, files in os.walk(path) for filename in files for date in dateList if filename.endswith(date+".log")]
for item in files:
reg = re.search(r"(.+]).(\d{2}.\d{2}.\d{4})",item)
equip = reg.group(1)
data = reg.group(2)
namefile = data+'.'+equip
print item
- group(1) - [EQUIP-X]
- group(2) - Date
Sample String:
[EQUIP-4].02.05.2019.log
[EQUIP-2].01.05.2019.log
[EQUIP-1].30.04.2019.log
[EQUIP-3].29.04.2019.log
[EQUIP-1].01.05.2019.log
[EQUIP-5].30.04.2019.log
[EQUIP-1].29.04.2019.log
[EQUIP-5].30.04.2019.log
[EQUIP-3].30.04.2019.log
[EQUIP-1].29.04.2019.log
[EQUIP-2].02.05.2019.log
Following this tutorial, there is not attribute 'sort' for 'str' object, once I'm not manipulating 'date' but 'str'. What is the better way to do it? The idea was to split and handle with date and after join all
Solution
You can just sort based on the end of the string minus the last 4 characters (the file extension) parsed as a date. Since the date format is zero padded, it should always be 10 characters long hence the string splice starting from -14 (10 for date + 4 for extension)
from datetime import datetime
files = ['[EQUIP-4].02.05.2019.log',
'[EQUIP-2].01.05.2019.log',
'[EQUIP-1].30.04.2019.log',
'[EQUIP-3].29.04.2019.log',
'[EQUIP-1].01.05.2019.log',
'[EQUIP-5].30.04.2019.log',
'[EQUIP-1].29.04.2019.log',
'[EQUIP-5].30.04.2019.log',
'[EQUIP-3].30.04.2019.log',
'[EQUIP-1].29.04.2019.log',
'[EQUIP-2].02.05.2019.log']
files.sort(key=lambda x: datetime.strptime(x[-14:-4], '%d.%m.%Y'))
print(files)
['[EQUIP-3].29.04.2019.log',
'[EQUIP-1].29.04.2019.log',
'[EQUIP-1].29.04.2019.log',
'[EQUIP-1].30.04.2019.log',
'[EQUIP-5].30.04.2019.log',
'[EQUIP-5].30.04.2019.log',
'[EQUIP-3].30.04.2019.log',
'[EQUIP-2].01.05.2019.log',
'[EQUIP-1].01.05.2019.log',
'[EQUIP-4].02.05.2019.log',
'[EQUIP-2].02.05.2019.log']
Answered By - Sayse
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.