Sort strings by the first N characters

后端 未结 2 2064
野趣味
野趣味 2021-01-04 23:44

I have a text file with lines like this:

2010-02-18 11:46:46.1287 bla
2010-02-18 11:46:46.1333 foo
2010-02-18 11:46:46.1333 bar
2010-02-18 11:46:46.1467 bla
         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 00:25

    The built-in sort is stable, so you the effectively-equal values stay in order by default.

    import operator
    
    with open('filename', 'r') as f:
        sorted_lines = sorted(f, key=operator.itemgetter(slice(0, 24)))
    

    At this point sorted_lines will be a list of the sorted lines. To replace the old file, make a new file, call new_file.writelines(sorted_lines), then move the new file over the old one.

提交回复
热议问题