Veejay
Veejay

Reputation: 565

Outputting filenames in the same order as in directory - Python

I am trying to create a .txt file that reads all the filenames in a given directory and outputs the names without file extension onto a new .txt file. For ex: if my /images directory has img_1.jpg, img_2.jpg, img_4.jpg, img_4.jpg then this script will create a txt file with having img1, img2, img3, img4 I have a script that does a good job at creating the txt file, but the order in which the names are output is different from the order in which the images in my directory are placed.

import os    
files_no_ext = [".".join(f.split(".")[:-1]) for f in os.listdir() if os.path.isfile(f)]

with open('trainval.txt', 'w') as f:
    for s in files_no_ext:
        f.write("%s\n" % s)

the image directory has images in the following order:

banana-0.jpg
banana-1.jpg
banana-2.jpg
.
.
banana-1000.jpg

But the output in the .txt file is:

banana-0
banana-1
banana-10
banana-100
banana-1000
banana-1001
banana-1002
banana-1003
banana-1004
banana-1005
banana-1006
banana-1007
banana-1008
banana-1009

How can I ensure that the output is in the same order as the order of images in the directory?

Upvotes: 2

Views: 808

Answers (1)

alexisdevarennes
alexisdevarennes

Reputation: 5632

listdir() preserves the order of your file system.

See:

Python - order of os.listdir

Nonalphanumeric list order from os.listdir() in Python

To sort your list based the numeric value in the file names:

Use sorted and regex to sort on the numeric value of the file name.

import re
import os  

files_no_ext = [".".join(f.split(".")[:-1]) for f in os.listdir() if os.path.isfile(f)]

files_no_ext = sorted(files_no_ext , key=lambda x: (x, int(re.sub('\D','', x)), x))

with open('trainval.txt', 'w') as f:
    for s in files_no_ext:
        f.write("%s\n" % s)
   # Could also do: f.write("\n".join(files_no_ext))

Using mode="a" on open() is also probably better (mode="a" means append)

Upvotes: 2

Related Questions