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

What I want is something like

file_01_001

file_02_002

file_03_003

file_04_004

file_01_005

file_02_006

...

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?

解决方案

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.

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

import os

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

To sort file names:

#grab last 4 characters of the file name:

def last_4chars(x):

return(x[-4:])

sorted(file_list, key = last_4chars)

So it looks as follows:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值