Python - os.listdir 的顺序 [英] Python - order of os.listdir
问题描述
我是 Python 新手,我正在编写一个脚本,该脚本读取目录(仅包含文件)中的所有文件.我知道我可以使用这样的循环获取文件:
I'm new in Python and I'm working on a script that reads all the files in a directory (which contains only files). I know that I can get the files using a loop like this:
for file in os.listdir("my directory"):
或使用此语法的文件列表:
Or a list of files using this syntax:
files = [f for f in os.listdir("my directory ")]
问题是我以完全随机的顺序获取文件.我使用 sort
命令对我的列表进行排序解决了我的问题,但是,我仍然想知道:
The problem is that I get the files in a completely random order. I solved my problem using a sort
command to get my list sorted, but, I am still left wondering:
Python如何对listdir
方法返回的文件进行排序?
How does Python sort the files that are returned by the listdir
method?
推荐答案
此问题已在 SO 上解决,例如,此处:Python 中 os.listdir() 的非字母数字列表顺序
This question has been addressed on SO, for example, here: Nonalphanumeric list order from os.listdir() in Python
看起来 Python 返回的是本地文件系统使用的顺序,之后您必须对它们进行排序.
Looks like Python returns the order that the native filesystem uses, and you have to sort them afterwards.
这篇关于Python - os.listdir 的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!