pythonos.walk

OS.walk prints my files in a random order, how can i sort the values?


I am trying to export six images from a folder the six images are called 1.png, 2.png etc but when I call os.walk and ask to print the files they come out in a random order:

/Users/claudiabergeron/Documents/Python/Python_VideoGame_3.10/bin/python "/Users/claudiabergeron/Documents/Python/Tutoriels/Video games/Pygame/Platformer/help.py"
('/Users/claudiabergeron/Documents/Python/Tutoriels/Video games/Pygame/Platformer/graphics/character/run', [], ['4.png', '5.png', '6.png', '2.png', '3.png', '1.png'])

Here is the code:

from os import walk
def import_folder(path):

    for information in walk(path):
        print(information)

import_folder('/Users/leolepage/Documents/Python/Tutoriels/Video games/Pygame/Platformer/graphics/character/run')

Does anybody know what should I do?


Solution

  • os.walk uses os.listdir and cannot be sorted. i would suggest you use os.listdir and sort it:

    from os import listdir
    def import_folder(path):
        for information in sorted(listdir(path)):
            print(information)