Wizard
Wizard

Reputation: 22113

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?

Upvotes: 1

Views: 133

Answers (1)

Albin Paul
Albin Paul

Reputation: 3419

Its easy if you read the documentation of os.listdir

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory.

That means the os.listdir command always has

no_of_elements_in(`ls -a`)-no_of_elements_in(".. and  .")

that is

len('os.listdir') =no_of_elements_in(`ls -a`)-2

In your case 474=476-2

Upvotes: 1

Related Questions