简体   繁体   中英

which command is better: os.listdir() or os.system('ls') and WHY?

In the current working directory:

import os
print( os.listdir() )

will list the files and directories. However, I could also get a list of the files and directories in the current working directory of a Linux machine using the system command:

import os
print( os.system('ls') )

Which command is better: os.listdir() or os.system('ls') and why?

os.listdir() is implemented natively in python, and will work on any operating system that python is compiled on.

Calling os.system('ls') relies on the underlying operating system to have an ls command, which is a wild assumption (eg, what about windows?), and requires this executable to be in the $PATH . From a performance standpoint, you'd be executing another process, which is completely redundant. And if you want to do anything fancier than just printing the result, you'll have to mess around with parsing the output yourself.

To make a long story short - don't reinvent the wheel. If python gives you a built-in os.listdir() , just use it.

I maybe digging graves here but I recently came across a similar usage.

I tried to ls a /path/to/temp file. It did not work, the ls command would get stuck and unresponsive, for more than 5 minutes before I shut it down. notice this was over SSH via putty, I tried ls -l | wc -l ls -l | wc -l , which didn't work either.

len(os.listdir("path/to/temp")) returned a number immediately, and it was around 75000 , the list was constructed nearly immediately. So there is a clear speed advantage if you use os.listdir() vs ls on directory with a large number of descendants.

Just to pile on: ls has an overhead limit to the number of files in the directory you are trying to use it on. os.listdir() suffers no such limitation. If you can use it, then os.listdir() seems to be the superior choice.

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