top of page

OS Module in Python for Handling Files and Directories?

Updated: Jan 28, 2023

OS Module allows us to access functionality of the underlying operating system. So, we can perform tasks such as: navigate the file system, obtain file information, rename files, search directories recursively, and many other operations.


some basic operations to change directory, to get current working directory, to create a new directory, and removing a directory:

os.listdir ()

os.listdir () will print all files and directories under the current path, If you want to print the results based on another path, just give the os.listdir (desired_path) function with arguments.


If you want to get a list of files only, we can use the list comprehension syntax:


prints only files, excluding directories:

prints only directories, excluding files:

os.walk()

walk () method walks recursively all sub-directories, it returns a generator, every time you call the next () method to generate its next value. It returns a tuple (dir_path, dir_names, file_names).


- dir_path is the current path.

- dir_names is a list of directories under current path.

- file_names is a list of all file names.

Glob Module to Search by Regular Expressions

Instead of getting all file names, sometimes we would like to precisely get the names of a specific type of files.


to list all .log files from the current directory:

pathlib module

With the help of list comprehension tricks, we can just use one line of code to generate all file names of the current path:

os.scandir()

The classic os.listdir() function is intuitive but not efficient for large directories that contain a huge of files. Therefore, Python 3.5 introduced a new similar function - os.scandir (). This function will return a generator instead of a list of all names.

following two statements are returns home directory in windows:

 

Thanks for reading!!!

Your Rating and Review will be appreciated!!

Twitter: @LearnerLandmark

Recent Posts

See All
bottom of page