Python code to list all files in a directory
Python contains useful modules to execute file and folder operations. It makes use of the ‘os’ module to carry out file system operations. To illustrate, the python code to get the current working directory is:
import os
os.getcwd()
.
On OSX, the output of that is:
'/Users/vikrambahl/Documents'
.
The ‘os’ module makes it easy to manipulate files and folders on a file system. To list all the files in a directory, you type in the following code:
import os
os.listdir(os.getcwd())
The piece of code above will return a list of all the files contained in the directory specified within the parentheses of ‘os.listdir()’. In this case, it will list out all the files contained in the current directory as specified by the function call ‘os.getcwd()’.
The usage is:
os.listdir()
The output of the command on idle is something like:
['.DS_Store', '.localized', 'Digital Editions', 'Microsoft User Data', 'RDC Connections', 'signal_processing', 'wallapers']
Find out more about the ‘os’ module at the python docs.
comments powered by Disqus