Python-os.listdir的顺序 [英] Python - order of os.listdir

查看:603
本文介绍了Python-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆