python - 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'
解决方案
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
推荐阅读
- protractor - 詹金斯工作没有生成黄瓜报告
- dom - PIXI 检查是否将 DisplayObject 添加到舞台或从舞台中删除
- c# - EF TPT 尝试映射到单个表
- c# - 网络核心异常处理程序 lambda 创建重复项
- java - 在 JLabel 上打印一个正方形并将其存储在作为 JLabel 内容的图像中
- swift - 如何指定在 Swift 中使用泛型重载函数?
- c++ - 如何避免 nullchar 转换为 0?
- r - 两年值之间的比率
- python-3.x - Pandas Dataframe 显示问题 IBM Watson Notebook
- jquery - 使用jquery在laravel中单击按钮时如何获取foreach中数组的值索引