0

I have 40k images in a folder. The file names follow the following pattern:

1558058263_18ea873ddcf8c65e.jpg
1558408930_63c29ce4462ec194.jpg 
1558062887_18ea873ddcf8c65e.jpg

In this the first part of the file name is the time stamp and the second part is the machine id that generated the image.

I want to process each of these files in a sequential order based on only the time stamp. How can I take the files sequentially for processing. I am using python3 for selecting the files. The current code is as follows:

 for root, dirs, files in os.walk(path):
                for name in files:
                        img=fr.load_image_file('/home/ubuntu/faces/' + name)
2

It seems to me that you could use the sort() or sorted() functions (from Stack Overflow):

# ...
for root, dirs, files in os.walk(path):
   files.sort()
   for name in files:
      print(name)

or

# ...
for root, dirs, files in os.walk(path):
   for name in sorted(files):
      print(name)
  • Ah! Yeah, since the timestamp numbers are all the same length / number of digits, then sorting lexicographically will also work. – L. Scott Johnson Jun 11 at 17:24
  • @jeffschaller thank you...the files.sort() works as required. – Apricot Jun 12 at 3:50
  • Do keep in mind that this is a simplistic sort and will do the wrong thing in late November of 2286, about 267 years from now, when the timestamp becomes 11 digits long. Keep L. Scott Johnson's answer around for when that comes! – Jeff Schaller Jun 12 at 12:53
2

You might try sorting via a lambda (UNTESTED):

for root, dirs, files in os.walk(path):
    for name in sorted(files,  key=lambda x: int(re.search(r'\d+', x).group())):
        img=fr.load_image_file('/home/ubuntu/faces/' + name)
0

The sort command should give you what you want.

ls | sort -n -t '_' -k1

-n sorts numerically, instead of the default lexicographically.
-t '_' specifies _ as a field separator.
-k1 sorts on the first field.

  • That looks like shell commands, not python. – L. Scott Johnson Jun 11 at 13:10
  • 1
    The OP didn't specify they wanted a Python solution. If that's the case, this should be in Stack Overflow, not here. – scatter Jun 11 at 13:26
0

Tested and it worked fine

find . -type f -iname "*.jpg" 2>/dev/null| sed "s/\.\///g"| awk -F "_" '{print $1,$2}'| sort -k1| awk 'OFS="_" {print $1,$2}'

Will update with Python script asap

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.