Operating System Commands
Learn about the different functions present in the operating system module.
We'll cover the following
Introduction to OS commands
Python also provides you with a module that has operating system commands. Here are some of the functions available when you import os
:
-
Use
os.getcwd()
to get the current working directory. -
Use
os.chdir(
path
)
to change the current working directory topath
. -
Use
os.listdir(path=".")
to return a list containing the names of the entries in the directory"."
.- Note that
path
(not italicized) in thelistdir
method is a keyword, not a variable that can be replaced by some other name. In all the other functions,path
(italicized) represents a variable containing a string or the string itself.
- Note that
-
Use
os.mkdir(
path
,mode=0o777, dir_fd=None)
to create a directory namedpath
with numericmode 0o777
. Here, thedir_fd
is an optional parameter that is used as a unique identifier referring to a directory withNone
as the default value.The
mode
is a Unix-style three-digit octal code. The three bits of each digit specify read, write, and execute permissions for owner, group, and world. -
Use
os.remove(
path
,dir_fd=None)
to delete the single filepath
. This is not for directories. -
Use
os.rmdir(
path
,dir_fd=None)
to remove (delete) the empty directorypath
. -
Use
os.rename(src, dst)
to rename the file orsrc
directory todst
. -
Use
os.walk(top, topdown=True, onerror=None, followlinks=False)
to generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at the top directory (includingtop
itself), it yields a 3-tuple (dirpath
,dirnames
,filenames
).
Here’s an example of this :
Get hands-on with 1400+ tech skills courses.