如何使用python按特定顺序对文件名进行排序 [英] How to sort file names in a particular order using python

查看:1633
本文介绍了如何使用python按特定顺序对文件名进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法可以对python目录中的文件进行排序?我想到的文件以

Is there a simple way to sort files in a directory in python? The files I have in mind come in an ordering as

file_01_001
file_01_005
...
file_02_002
file_02_006
...
file_03_003
file_03_007
...
file_04_004
file_04_008

我想要的是类似的东西

file_01_001
file_02_002
file_03_003
file_04_004
file_01_005
file_02_006
...

我目前正在使用glob打开目录,如下所示:

I am currently opening them using glob for the directory as follows:

for filename in glob(path):    
    with open(filename,'rb') as thefile:
        #Do stuff to each file

因此,尽管程序执行所需的任务,但是由于文件顺序的原因,如果一次执行多个文件,则会给出错误的数据.有什么想法吗?

So, while the program performs the desired tasks, it's giving incorrect data if I do more than one file at a time, due to the ordering of the files. Any ideas?

推荐答案

如上所述,目录中的文件并不是固有地以特定方式排序的.因此,我们通常1)获取文件名2)通过所需属性对文件名进行排序3)以排序顺序处理文件.

As mentioned, files in a directory are not inherently sorted in a particular way. Thus, we usually 1) grab the file names 2) sort the file names by desired property 3) process the files in the sorted order.

您可以按以下方式获取目录中的文件名.假设目录为〜/home",那么

You can get the file names in the directory as follows. Suppose the directory is "~/home" then

import os

file_list = os.listdir("~/home")

要对文件名进行排序:

#grab last 4 characters of the file name:
def last_4chars(x):
    return(x[-4:])

sorted(file_list, key = last_4chars)   

它看起来如下:

In [4]: sorted(file_list, key = last_4chars)
Out[4]:
['file_01_001',
 'file_02_002',
 'file_03_003',
 'file_04_004',
 'file_01_005',
 'file_02_006',
 'file_03_007',
 'file_04_008']

要按顺序读入并处理它们,请执行以下操作:

To read in and process them in sorted order, do:

file_list = os.listdir("~/home")

for filename in sorted(file_list, key = last_4chars):    
    with open(filename,'rb') as thefile:
        #Do stuff to each file

这篇关于如何使用python按特定顺序对文件名进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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