The os Module
The os module provides a unified interface to many operating
system functions.
Most of the functions in this module are implemented by platform-specific modules, such as posix or nt. The os
module automatically loads the right implementation module when it
is first imported.
Working with Files
The built-in open function lets you create, open,
and modify files, as shown in Example 1-27. This module adds those extra functions you need to
rename and remove files.
Example 1-27. Using the os Module to Rename and Remove Files
File: os-example-3.py
import os
import string
def replace(file, search_for, replace_with):
# replace strings in a text file
back = os.path.splitext(file)[0] + ".bak"
temp = os.path.splitext(file)[0] + ".tmp"
try:
# remove old temp file, if any
os.remove(temp)
except os.error:
pass
fi = open(file)
fo = open(temp, "w")
for s in fi.readlines():
fo.write(string.replace(s, search_for, replace_with))
fi.close()
fo.close()
try:
# remove old backup file, if any
os.remove(back)
except os.error:
pass
# rename original to backup...
os.rename(file, back)
# ...and temporary to original
os.rename(temp, file)
#
# try it out!
file = "samples/sample.txt"
replace(file, "hello", "tjena")
replace(file, "tjena", "hello")Working with Directories
The os module also contains many functions that work on entire
directories.
The listdir function returns a list of all
filenames in a given directory, as shown in Example 1-28. The current and parent directory markers used ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access