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
# create a new directory
# list the contents of a directory
# remove directory
# remove a file
# 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

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
# split a path into a the final directory/file and the rest of the path
# split path to find the file type - eg. ".doc"

You may also like