Python os.listdir 是字典序顺序吗/ 排序规则
2022/4/22 11:12:44
本文主要是介绍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 是字典序顺序吗/ 排序规则的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器
- 2024-11-16四种数据科学Web界面框架快速对比:Rio、Reflex、Streamlit和Plotly Dash
- 2024-11-14获取参数学习:Python编程入门教程
- 2024-11-14Python编程基础入门