Home » Python os Module

Python os Module

by Jack Simpson

You can use the Python os module to send commands out to the operating system. Through os you can do anything from changing the current working directory through to listing the contents of a directory.

import os

# print the current working directory
print os.getcwd()
# change the working directory
os.chdir("..")
# create a new directory
os.mkdir("new_folder")
# list the contents of a directory
os.listdir("new_folder")
# remove directory
os.rmdir("new_folder")
# remove a file
os.remove("image.jpg")
# rename a file/directory and where it will go
os.rename("/data/jack", "/james")

The os.listdir command can be extremely useful, and with a little more code  you can run some checks on the contents of the directory you’re looking in:


# check if you're looking at a file or directory
os.path.isdir("afolder")
os.path.isfile("image.jpg")

Finally, I’d like to talk about the os.path class, which allows you to specify the path to directories on all operating systems (remembering that in windows the path separator is a “” while on a Mac/Linux machine it is a “/”.


# join together a path which will work on linux, windows and macs
os.path.join("os.getwcw(), "data")
# check if a path exists
os.path.exists("/data/research/paper")
# split a path into a the final directory/file and the rest of the path
os.path.split("/data/research/measurements.doc")
# split path to find the file type - eg. ".doc"
os.path.splitext("/data/test/img.jpg")

You may also like