search

Home  >  Q&A  >  body text

The order problem of Python's os.listdir when obtaining the file list

This is the file order displayed in Windows Explorer

The list order obtained by using os.listdir is like this:
['03.jpg', '1.jpg', '2.jpg', '3.jpg', '5.jpg' , '6.png', 'test.url']

How can I get the file list in the same order as Windows Explorer?

PHP中文网PHP中文网2737 days ago1817

reply all(1)I'll reply

  • 扔个三星炸死你

    扔个三星炸死你2017-06-28 09:28:11

    Let’s try it in order...

    import os
    result = os.listdir('.')
    result.sort()
    print result

    But it feels like it’s not meaningful to ask for the same order as the resource manager. Because the list in the resource manager may be in order of modification time, name, or some other unknown order..

    Sort by modification time, you can adjust it yourself

    import os
    result = [(i, os.stat(i).st_mtime) for i in os.listdir('.')]
    for i in sorted(result, key=lambda x: x[1]):
        print i[0]
    

    reply
    0
  • Cancelreply