以升序对目录中的文件名进行排序

编程入门 行业动态 更新时间:2024-10-22 19:24:01
本文介绍了以升序对目录中的文件名进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含jpgs和其他文件的目录,所有jpgs的文件名中都带有数字.有些可能在文件名中包含其他字符串.

I have a directory with jpgs and other files in it, the jpgs all have filenames with numbers in them. Some may have additional strings in the filename.

例如.

01.jpg

或者可能是

Picture 03.jpg

在Python中,我需要按升序排列所有jpg的列表. 这是此代码段

In Python I need a list of all the jpgs in ascending order. Here is the code snippet for this

import os import numpy as np myimages = [] #list of image filenames dirFiles = os.listdir('.') #list of directory files dirFiles.sort() #good initial sort but doesnt sort numerically very well sorted(dirFiles) #sort numerically in ascending order for files in dirFiles: #filter out all non jpgs if '.jpg' in files: myimages.append(files) print len(myimages) print myimages

我得到的是这个

['0.jpg', '1.jpg', '10.jpg', '11.jpg', '12.jpg', '13.jpg', '14.jpg', '15.jpg', '16.jpg', '17.jpg', '18.jpg', '19.jpg', '2.jpg', '20.jpg', '21.jpg', '22.jpg', '23.jpg', '24.jpg', '25.jpg', '26.jpg', '27.jpg', '28.jpg', '29.jpg', '3.jpg', '30.jpg', '31.jpg', '32.jpg', '33.jpg', '34.jpg', '35.jpg', '36.jpg', '37.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg']

很显然,它首先盲目地对最高有效数字进行排序.我尝试使用sorted(),因为您可以看到它希望能够解决该问题,但没什么区别.

Clearly it sorts blindly the most significant number first. I tried using sorted() as you can see hoping that it would fix it but it makes no difference.

推荐答案

假定每个文件名中只有一个数字:

Assuming there's just one number in each file name:

>>> dirFiles = ['Picture 03.jpg', '02.jpg', '1.jpg'] >>> dirFiles.sort(key=lambda f: int(filter(str.isdigit, f))) >>> dirFiles ['1.jpg', '02.jpg', 'Picture 03.jpg']

一个也可以在Python 3中使用的版本:

A version that also works in Python 3:

>>> dirFiles.sort(key=lambda f: int(re.sub('\D', '', f)))

更多推荐

以升序对目录中的文件名进行排序

本文发布于:2023-11-01 17:57:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550015.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:升序   文件名   目录中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!