• No results found

File System

In document Making Use of Python (Page 169-174)

Python has separate modules for different operating systems, such as posix for Unix, ntfor Windows, and mac for Macintosh, to perform file- and directory-related tasks. The use of methods in these modules is slightly complex, though. The os module pro- vides methods, which are simple to use, for performing file- and directory-related tasks. The os module acts as a front-end module to a pure operating system-dependent module. This module eliminates the direct use of operating system-dependent modules by loading appropriate modules according to the operating system installed on a computer.

You can divide the methods in the os module into three categories: ■■ File processing

■■ Directory ■■ Permissions

Let’s discuss these methods in detail.

File-Processing Methods

The os module provides methods that help you perform file-processing operations, such as renaming and deleting files. You can rename files by using the rename() method and delete files by using the remove() method. Let’s look at the functioning of these methods.

The rename() Method. The rename() method takes two arguments, the cur- rent filename and the new filename. The syntax for the rename() method is:

The following example renames myfile to newfile.

>>>import os

>>>os.rename(‘myfile’, ‘newfile’)

When you execute this code, the os module converts this method to the appro- priate rename command based on the operating system installed.

The remove() Method. You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument. The following code displays the use of the remove() method.

>>>import os

>>>os.remove(‘newfile’)

Directory Methods

The os module has several methods that help you create, remove, and change directo- ries. You can also use directory methods to display the current directory and list the contents of a directory.

The mkdir() Method. You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created. The follow- ing code creates a directory called newdir:

>>> import os

>>>os.mkdir(‘newdir’)

N OT E

The osmodule has one more method that allows you to create

directories—makedirs(). This method also takes the name of the directory to be created as the argument.

The chdir() Method. You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory. For example, you can change the current directory from home to the directory newdir by using the following code:

>>> import os

>>>os.chdir(‘newdir’)

The getcwd() Method. The getcwd() method displays the current working directory. The following code displays the use of the getcwd() method:

>>> import os >>> os.getcwd() ‘/home/newdir’ >>>os.chdir(‘/home’) >>> os.getcwd() ‘/home’

The listdir() Method. You can display the contents of a directory, which com- prises files and subdirectories, by using the listdir() method. This method takes the name of the directory for which the contents are to be displayed as the

argument. For example, you can display the contents of the directory newdir by using the following code:

>>>import os

>>> os.listdir(‘newdir’) [‘File1’, ‘File2’]

The last line in this code is the result obtained by executing the second line of code.

The rmdir() Method. The rmdir() method deletes the directory, which is passed as an argument in the method. Before removing a directory, all the contents in it should be removed. You can delete newdir by using the following code:

>>> import os >>>os.chdir(‘newdir’) >>>os.remove(‘File1’) >>>os.remove(‘File2’) >>>os.chdir(‘/home’) >>>os.rmdir(‘newdir’)

N OT E

You can also delete directories by using the removedirs()method

of the osmodule. In this method also, you need to supply the name of the directory to be deleted as the argument.

Permission Methods

The permission methods of the os module allow you to set and verify the permission modes. Table 7.3 describes the different permission methods.

The os.path Module

The os.path module includes functions that are useful to perform path-related oper- ations. You can access the os.path module from the os module. The methods avail- able in this module are useful for operations such as file path inquiries and retrieving information about files and directories. Let’s look at the most useful methods of the os.pathmodule.

Table 7.3 The Access Permission Methods of the osModule

METHOD DESCRIPTION

os.access(path,mode) This method verifies the access permission specified in the mode argument to the specified path. If the access permission is granted, the access()method returns 1. Otherwise, this function returns 0.

os.chmod(path, mode) This method changes the access permission of the pathto the specified mode.

umask(mask) This method sets the mask specified as the argument and returns the old mask.

The basename() Method. The os.path.basename() method takes a path name as an argument and returns the leaf name of the specified path. For exam- ple, you have created a file called file1 in a directory called user1 under the homedirectory. Now, you can use the basename() method to retrieve only the filename from the path /home/user1/file1 by using the following code:

>>> import os

>>>os.path.basename(‘/home/user1/file1’) ‘file1’

The dirname() Method. You can use the os.path.dirname() method to retrieve the directory name from a path name. For example, the following code returns the directory name of the path ‘/home/user1/file1’:

>>> import os

>>> os.path.dirname(‘/home/user1/file1’) ‘/home/user1’

The join() Method. The os.path.join() method joins two or more path components into a single path name. This method takes the path components as arguments. The following example illustrates the use of the join() method:

>>>import os >>>current_dir=os.getcwd() >>> print current_dir /home/ >>>join_dir=os.path.join(current_dir,’testfile’) >>>print join_dir /home/testfile

This example joins the path of the current working directory with the second argument, testfile, and returns the joined path.

The split() Method. The os.path.split() method splits a path, which is passed as an argument, into a directory name and a base name and returns them as a tuple. The following example splits the joined path obtained in the previous example:

>>> import os.path

>>> os.path.split(join_dir) (‘/home’,’testfile’)

The splitdrive() Method. The splitdrive() method is used to split the drive name and the path name of the argument passed in the method. The fol- lowing examples illustrate the use of the splitdrive() method in both Unix and Windows versions:

■■ Unix version >>> import os.path >>> os.path.splitdrive(‘/home/testfile’) (‘’, ‘/home/ testfile’) ■■ Windows version >>> import os.path >>> os.path.splitdrive(‘c:/Python’) (‘c:’, ‘/Python’)

Table 7.4 The Information Methods of the os.pathModule

METHOD DESCRIPTION

getsize(file_name) Returns the size of a file in bytes

getatime(file_name) Returns the time when a file was last accessed getmtime(file_name) Returns the time when a file was last modified

The splitext() Method. The splitext() method separates the first name and the extension name of a filename. Consider the following code:

>>> import os.path

>>> os.path.splitext(‘testfile.txt’) (‘testfile’, ‘.txt’)

The Information Methods

The os.path module has three methods that allow you to retrieve information about the file size and file access. Table 7.4 describes these methods.

The following example displays the functioning of these methods:

>>> import os.path >>> os.path.getsize(‘testfile’) 47L >>> os.path.getatime(‘testfile’) 1006535165 >>> os.path.getmtime(‘testfile’) 1006541232

Other Useful Methods

The os.path module also has certain methods that help to determine the existence of path names, directories, and files. Table 7.5 describes the important methods of the inquiry category.

Table 7.5 The Inquiry Category Methods of the os.pathmodule

METHOD DESCRIPTION

exists(path_name) Returns 1 if path_name exists and 0 if path_name does not exist

isdir(path_name) Returns 1 if path_name is a directory and 0 otherwise

Now, let’s discuss how we can use these methods. >>> import os.path >>> os.path.exists(‘/home’) 1 >>> os.path.exists(‘/home/testfile’) 1 >>> os.path.isdir(‘/home’) 1 >>> os.path.isdir(‘/home/testfile’) 0 >>> os.path.isfile(‘/home’) 0 >>> os.path.isfile(‘/home/testfile’) 1

In this example, the exists() method returns 1 in both the cases because both the paths exist. The isdir() methods return 1 and 0, and the isfile() methods return 0 and 1 because /home is a directory and testfile is a file. You have learned about all the important file objects. Now, let’s decide the methods to be used to solve the problem statement given in the beginning of the chapter.

Result

You need to store course details to a file and display the contents of that file. To do this, you need to use the following methods:

■■ open()

In document Making Use of Python (Page 169-174)