首页 > 解决方案 > I'm trying to keep my csv files in monthly order like may, jun etc and trying to change the order with python, but unable to do that

问题描述

I'm trying to keep my csv files in monthly order like may, jun etc and trying to change the order with python, but unable to do that.

My csv file names are jun01.csv, jun02.csv, jun03.csv, may03.csv, may04.csv. I want to change that according to monthly order like may03.csv, may04.csv, jun04.csv etc.

The code is below

import collections
import os

path = r'Stocks'
all_files = os.listdir(path)
filenames = []
for filename in all_files:
    if filename.endswith(".csv"):
        filenames.append(filename)

y = [z[:3] for z in filenames]


def lst(string):
    str1 = " "

    return str1.join(y)


print(lst(y))
------------------------------
Output is :
    
jun jun jun jun may may may may may may may may may may may may may may may may may may may may
------------------------------

# Code Continued


def rearrange(seq, order, keyfunc):
    if not isinstance(order, collections.Mapping):
        order = {v: i for i, v in enumerate(order)}
    return sorted(seq, key=lambda x: order[keyfunc(x)])


if __name__ == '__main__':
    filenames = lst(y).split()

    months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul',
              'aug', 'sep', 'oct', 'nov', 'dec']


    def get_month_name(filename):
        return filename.split(' ')


    for filename in rearrange(filenames, months, get_month_name):
        print(filename)

It's throwing error like :

File "C:month_sort.py", line 43, in <module>
    for filename in rearrange(filenames, months, get_month_name):
  File "C:month_sort.py", line 27, in rearrange
    return sorted(seq, key=lambda x: order[keyfunc(x)])
  File "C:month_sort.py", line 27, in <lambda>
    return sorted(seq, key=lambda x: order[keyfunc(x)])
TypeError: unhashable type: 'list'

标签: pythonpython-3.xlistfunctionsorting

解决方案


I don't know if this is what you want but it sorts the file according to their months :

def rearrange(seq, order, keyfunc):
    if not isinstance(order, collections.Mapping):
        order = {v: i for i, v in enumerate(order)}
    return sorted(seq, key=lambda x: order[keyfunc(x)])


if __name__ == '__main__':

    months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul',
              'aug', 'sep', 'oct', 'nov', 'dec']


    def get_month_name(filename):
        return filename[:3]

    for filename in rearrange(filenames, months, get_month_name):
        print(filename)

Tell me if you wanted something else to happen


推荐阅读