首页 > 解决方案 > 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?

标签: python

解决方案


如果您阅读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


推荐阅读