阅读前如何对目录中的文件进行排序? [英] How to sort files in a directory before reading?

查看:102
本文介绍了阅读前如何对目录中的文件进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个程序,该程序根据从目录中读取文件的顺序将输出写入csv文件.但是,大量文件的结尾为1,2,3,4,5,6,7,8,9,10,11,12.我的程序实际上是按字母顺序读取文件的:1,10,11,12 ....,2,20,21 ..... 99.问题在于另一个程序假定该排序是按数字顺序进行的,并且使图形结果偏斜.

I am working with a program that writes output to a csv file based on the order that files are read in from a directory. However with a large number of files with the endings 1,2,3,4,5,6,7,8,9,10,11,12. My program actually reads the files by I guess alphabetical ordering: 1,10,11,12....,2,20,21.....99. The problem is that another program assumes that the ordering is in numerical ordering, and skews the graph results.

实际文件如下:String.ext.ext2.1.txt, String.ext.ext2.2.txt,依此类推...

The actually file looks like: String.ext.ext2.1.txt, String.ext.ext2.2.txt, and so on...

如何使用python脚本执行此操作?

How can I do this with a python script?

推荐答案

files = ['String.ext.ext2.1.txt', 'String.ext.ext2.12.txt', 'String.ext.ext2.2.txt']
# files: coming from os.listdir() sorted alphabetically, thus not numerically

sorted_files = sorted(files, key=lambda x: int(x.split('.')[3]))
# returns: ['String.ext.ext2.1.txt', 'String.ext.ext2.2.txt', 'String.ext.ext2.12.txt']

这篇关于阅读前如何对目录中的文件进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆