python - os.listdir print more files than command `ls` but less than `ls -a`
问题描述
I'd like to count the command in path /Users/me/anaconda3/bin
In [3]: len(os.listdir("/Users/me/anaconda3/bin"))
Out[3]: 474
However, when I check with commands
In [5]: !count=0; for f in $(ls /Users/me/anaconda3/bin) ;do count=$(( $count + 1)); done; echo $count
470
However, if check all the files:
In [17]: ls -a /Users/me/anaconda3/bin | wc -l
476
What's the reason cause the difference?
解决方案
如果您阅读os.listdir的文档,这很容易
返回一个列表,其中包含路径给定的目录中条目的名称。该列表按任意顺序排列,不包括特殊条目“.”。和 '..' 即使它们存在于目录中。
这意味着 os.listdir 命令总是有
no_of_elements_in(`ls -a`)-no_of_elements_in(".. and .")
那是
len('os.listdir') =no_of_elements_in(`ls -a`)-2
在你的情况下474=476-2
推荐阅读
- vba - 使用 Visual Basic 移动线条和书签
- java - 如何防止 Spring 记录警告“osweb.servlet.PageNotFound”?
- sql-server - 在 SQL Server 数据库表中的十进制(18,6)列中插入 2,147,483,648 或更大时,算术溢出转换为 int
- reactjs - react-navigation 5中的嵌套堆栈
- r - 根据数字序列对 R 中的列进行排序
- javascript - 无法正确获取客户的反应 - discord.js
- c# - Unity - 将 Lerped 位置反转回原始位置
- javascript - JS,如何将没有分隔符的字符串格式化为日期
- node.js - 关于 socket.io 和 SameSite 属性的跨站点请求的 chrome 警告问题
- javascript - Material UI iFrame 错误不可点击且音量未静音