Python按文件排序顺序

时间:2016-06-10 05:31:13

标签: python

我为程序编写了以下代码,以显示文件夹中的图像路径名称。但是,如输出中所示,图片'尽管我使用了排序,但路径没有以正确的顺序显示。如何按排序顺序显示它们?

代码:

import os
import sys
from PIL import Image
import PIL.ImageOps
import glob

path="/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/"
print(path)
files=sorted(glob.glob(path+"*.JPG"))
#print(files)
file_index=0
for f in files:
    file_index=file_index+1
    print(f,file_index)

输出:

/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/1.JPG 1
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/10.JPG 2
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/11.JPG 3
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/12.JPG 4
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/13.JPG 5
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/14.JPG 6
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/2.JPG 7
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/3.JPG 8
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/4.JPG 9
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/5.JPG 10
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/6.JPG 11
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/7.JPG 12
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/8.JPG 13
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/9.JPG 14

2 个答案:

答案 0 :(得分:3)

这应该有效,假设文件名是数字。

import os
import sys
from PIL import Image
import PIL.ImageOps
import glob

path = "/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/"
print(path)
files = glob.glob(path+"*.JPG")
n = [int(i) for i in map(lambda x: x.split('/')[-1].split('.jpg')[0], files)]
files = [x for (y, x) in sorted(zip(n, files))]
print(files)

基本上,您的代码不起作用,因为您将文件排序为strings

答案 1 :(得分:2)

正如其他人所说,你正在比较字符串。 您可以为此创建自定义比较器:

files = glob.glob(path+"*.JPG")
sortedfiles = sorted(files, key=lambda filepath: int(filepath.split('/')[-1].split('.jpg')))

整个片段:

import os
import sys
from PIL import Image
import PIL.ImageOps
import glob

path="/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/"
print(path)
files=glob.glob(path+"*.JPG")
sortedfiles = sorted(files, key=lambda filepath: int(filepath.split('/')[-1].split('.jpg')[0]))

for f in sortedfiles:
    file_index=file_index+1
    print(f,file_index)