Python教程

Python os.listdir 是字典序顺序吗/ 排序规则

本文主要是介绍Python os.listdir 是字典序顺序吗/ 排序规则,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

os.listdir的排序不是字典序,是按照文件系统当中的文件节点顺序组织的

这种排序在不改动文件夹的情况下一般是确定的(可复现的),但没有确定的排序规则

即使是相同的文件,在不同的文件系统以及文件系统设置下也是不一样的

所以,应该用sorted(os.listdir)来生成确定性的结果


答案来自 https://stackoverflow.com/a/31535297

In order to understand what is going on we can inspect the underlying implementation for python 3.2 that can be found here.

We will focus on the POSIX part that starts at line 2574.
In the code are defined:

DIR *dirp;              // will store the pointer to the directory
struct dirent *ep;      // will store the pointer to the entry

There are two important POSIX calls: opendir at line 2596 and readdir at line 2611.

As you can read from the readdir man page:

The readdir() function returns a pointer to a dirent structure representing the next directory entry in the directory stream pointed to by dirp. It returns NULL on reaching the end of the directory stream or if an error occurred.

So, readdir reads the next entry in the directory, but it is up to the file system implementation to define what is the next. You can read more about this topic here:

[...] Because this is a per-filesystem thing, it follows that the traversal order can be different for different directories on the same system even if they have the same entries created in the same order, either because the directories are using different filesystem types or just because some parameters were set differently on the different filesystems.

这篇关于Python os.listdir 是字典序顺序吗/ 排序规则的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!