简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM