9.7. File SystemAccess to your file system occurs mostly through the Python os module. This module serves as the primary interface to your operating system facilities and services from Python. The os module is actually a front-end to the real module that is loaded, a module that is clearly operating systemdependent. This "real" module may be one of the following: posix (Unix-based, i.e., Linux, MacOS X, *BSD, Solaris, etc.), nt (Win32), mac (old MacOS), dos (DOS), os2 (OS/2), etc. You should never import those modules directly. Just import os and the appropriate module will be loaded, keeping all the underlying work hidden from sight. Depending on what your system supports, you may not have access to some of the attributes, which may be available in other operating system modules. In addition to managing processes and the process execution environment, the os module performs most of the major file system operations that the application developer may wish to take advantage of. These features include removing and renaming files, traversing the directory tree, and managing file accessibility. Table 9.5 lists some of the more common file or directory operations available to you from the os module.
A second module that performs specific pathname operations is also available. The os.path module is accessible through the os module. Included with this module are functions to manage and manipulate file pathname components, obtain file or directory information, and make file path inquiries. Table 9.6 outlines some of the more common functions in os.path.
These two modules allow for consistent access to the file system regardless of platform or operating system. The program in Example 9.1 (ospathex.py) test drives some of these functions from the os and os.path modules. Example 9.1. os & os.path Modules Example (ospathex.py)
The os.path submodule to os focuses more on file pathnames. Some of the more commonly used attributes are found in Table 9.6. Running this program on a Unix platform, we get the following output: $ ospathex.py *** current temporary directory /tmp *** creating example directory... *** new working directory: /tmp/example *** original directory listing: [] *** creating test file... *** updated directory listing: ['test'] *** renaming 'test' to 'filetest.txt' *** updated directory listing: ['filetest.txt'] *** full file pathname: /tmp/example/filetest.txt *** (pathname, basename) == ('/tmp/example', 'filetest.txt') *** (filename, extension) == ('filetest', '.txt') *** displaying file contents: foo bar *** deleting test file *** updated directory listing: [] *** deleting test directory *** DONE Running this example from a DOS window results in very similar execution: C:\>python ospathex.py *** current temporary directory c:\windows\temp *** creating example directory... *** new working directory: c:\windows\temp\example *** original directory listing: [] *** creating test file... *** updated directory listing: ['test'] *** renaming 'test' to 'filetest.txt' *** updated directory listing: ['filetest.txt'] *** full file pathname: c:\windows\temp\example\filetest.txt *** (pathname, basename) == ('c:\\windows\\temp\\example', 'filetest.txt') *** (filename, extension) == ('filetest', '.txt') *** displaying file contents: foo bar *** deleting test file *** updated directory listing: [] *** deleting test directory *** DONE Rather than providing a line-by-line explanation here, we will leave it to the reader as an exercise. However, we will walk through a similar interactive example (including errors) to give you a feel for what it is like to execute this script one step at a time. We will break into the code every now and then to describe the code we just encountered. >>> import os >>> os.path.isdir('/tmp') True >>> os.chdir('/tmp') >>> cwd = os.getcwd() >>> cwd '/tmp' This first block of code consists of importing the os module (which also grabs the os.path module). We verify that '/tmp' is a valid directory and change to that temporary directory to do our work. When we arrive, we call the getcwd() method to tell us where we are. >>> os.mkdir('example') >>> os.chdir('example') >>> cwd = os.getcwd() >>> cwd '/tmp/example' >>> >>> os.listdir() # oops, forgot name Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: function requires at least one argument >>> >>> os.listdir(cwd) # that's better :) [] Next, we create a subdirectory in our temporary directory, after which we will use the listdir() method to confirm that the directory is indeed empty (since we just created it). The problem with our first call to listdir() was that we forgot to give the name of the directory we want to list. That problem is quickly remedied on the next line of input. >>> fobj = open('test', 'w') >>> fobj.write('foo\n') >>> fobj.write('bar\n') >>> fobj.close() >>> os.listdir(cwd) ['test'] We then create a test file with two lines and verify that the file has been created by listing the directory again afterward. >>> os.rename('test', 'filetest.txt') >>> os.listdir(cwd) ['filetest.txt'] >>> >>> path = os.path.join(cwd, os.listdir(cwd)[0]) >>> path '/tmp/example/filetest.txt' >>> >>> os.path.isfile(path) True >>> os.path.isdir(path) False >>> >>> os.path.split(path) ('/tmp/example', 'filetest.txt') >>> >>> os.path.splitext(os.path.basename(path)) ('filetest', '.ext') This section is no doubt an exercise of os.path functionality, testing join(), isfile(), isdir() which we have seen earlier, split(), basename(), and splitext(). We also call the rename() function from os. Next, we display the file, and finally, we delete the temporary files and directories: >>> fobj = open(path) >>> for eachLine in fobj: ... print eachLine, ... foo bar >>> fobj.close() >>> os.remove(path) >>> os.listdir(cwd) [] >>> os.chdir(os.pardir) >>> os.rmdir('example') Core Module(S): os (and os.path)
|