python - Sorting a list of strings based on the first element from split (datetime) -


i have long list of strings, separated commas (basically, csv files read line line strings, not performing split on separator):

lines[0] = "2017-08-01 13:45:58,mytext,mytext2,mytext3,etc" lines[1] = "2017-08-01 15:45:58,mytextx,mytext2x,mytext3x,etcx" lines[2] = "2017-08-01 19:45:58,mytexty,mytext2y,mytext3y,etcy" lines[3] = "..." 

from this post know following code should work if lines consist of datetimes:

lines_sorted = sorted(lines, key=lambda x: datetime.datetime.strptime(lines, '%y-%m-%d %h:%m:%s')) 

i thought use partition extract tuples lines in files, first element contains datetimepart:

for unsortedfile in glob('*.txt'):     open(unsortedfile, 'r') file:         lines = [line.rstrip('\n').partition(',') line in file]         lines_sorted = sorted(lines, key=lambda x: datetime.datetime.strptime(lines[0], '%y-%m-%d %h:%m:%s')) 

..but of course, not work "typeerror: list indices must integers or slices, not str" because lines[0] not referencing first tuple first item in lines-list. tried using .strptime(lines[lambda][0], '%y-%m-%d %h:%m:%s')) neither working.

i know doing wrong.. appreciated.

[edit] here's answer, friendly comments below:

for unsortedfile in glob('*.txt'):     open(unsortedfile, 'r', encoding="utf8") file: #read each unsorted file lines (list)         lines = [line.rstrip('\n') line in file]         lines_sorted = sorted(lines,                     key=lambda x: x.split(',', maxsplit=1)[0]                     )         lines.clear()     open(unsortedfile,'w', encoding="utf8") file: #overwrite file         line in lines_sorted:             file.write(line + '\n') 

basically key argument of sorted function must function takes list item , returns comparable object.
sorted sort list according image of list items function, not items themselves.

here example, mix of suggested solutions :

lines_sorted = sorted(lines,                       key=lambda x: x.split(',', maxsplit=1)[0]                      ) 

with code, every item has same date considered equal sorted.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -