Working with Files on Disk

Most of the key file-manipulation functions live in the os module and an associated module called os.path . To provide a degree of platform independence, os loads in the right module for your platform. os provides basic file-handling functions, and os.path handles operations on paths and filenames. On Windows, these modules are called nt and ntpath respectively, although they should always be referred to as os and os.path. The functions in the os module generally accept the same arguments as their corresponding MS-DOS commands. Table 17.1 depicts the os module’s file and directory functions.

Table 17.1. File and Directory Functions

Module and Function

Description

os.getcwd()

Gets the current working directory.

os.chdir(newdir)

Changes the current working directory.

os.rmdir(dir)

Removes a directory, if allowed.

os.mkdir(newdir)

Creates a directory, supplies either an absolute path or a subdirectory name to go under the current directory.

os.exists(name)

Says if something exists, but doesn’t say if it’s a file or directory.

os.isdir(dirname)

Says that a directory exists.

os.isfile(filename)

Says that a file exists. filename may include a path; if not, it looks in the current directory.

os.listdir(dirname)

Returns a list of the files and directories within the given directory.

glob.glob(pattern)

Returns a list of files matching the given pattern (using expressions such as dir *.doc is known as file globbing on Unix, hence the ...

Get Python Programming On Win32 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.