OS.walk 以随机顺序打印我的文件,我该如何对值进行排序?

问题描述 投票:0回答:1

我正在尝试从一个文件夹中导出六张图片,这六张图片分别称为 1.png、2.png 等 但是当我打电话给 os.walk 并要求打印文件时,它们以随机顺序出现:

/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'])

代码如下:

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')

有人知道我该怎么办吗?

python os.walk
1个回答
2
投票

os.walk 使用os.listdir,无法排序。我建议你使用 os.listdir 并对其进行排序:

from os import listdir
def import_folder(path):
    for information in sorted(listdir(path)):
        print(information)
© www.soinside.com 2019 - 2024. All rights reserved.