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.
Module and Function |
Description |
os.getcwd() |
Gets the current working directory. |
os.chdir(
|
Changes the current working directory. |
os.rmdir(
|
Removes a directory, if allowed. |
os.mkdir(
|
Creates a directory, supplies either an absolute path or a subdirectory name to go under the current directory. |
os.exists(
|
Says if something exists, but doesn’t say if it’s a file or directory. |
os.isdir(
|
Says that a directory exists. |
os.isfile(
|
Says that a file exists. |
os.listdir(
|
Returns a list of the files and directories within the given directory. |
glob.glob(
|
Returns a list of files matching the given pattern (using expressions
such as |
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.