ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-04-22 09:33:36  阅读:185  来源: 互联网

标签:listdir Python pointer different readdir directory 排序 os


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.

标签:listdir,Python,pointer,different,readdir,directory,排序,os
来源: https://www.cnblogs.com/zxyfrank/p/16177454.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有