Python Programming Fundamentals for Class 11 and 12 – File Handling

There are several ways to present the output of a program; data can be printed on computer monitor in a human-readable form, or written to a file (for example, image.jpg, notes.txt, etc.) for future use. A computer file (or simply “file”) is a resource for storing information, which is available to a computer program, and is usually based on some kind of durable electronic storage. A file is durable in the sense that it remains available for programs to use after the current program has finished. Computer file can be considered as the modern counterpart of paper document which traditionally are kept in office files, library files, etc., and this is the source of the term.

File opening
A common operation needed during program execution is to load data from an existing file or to create a new file to store data. To accomplish this, the program first needs to open a file, which is executed using open () function. The open () returns a file object, and is most commonly used with two arguments, filename and mode.

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used, mode can be ‘ r ‘ when the file will only be read, ‘ w’ for only writing (an existing file with the same name will be erased), and ‘ a’ opens the file for appending, any data written to the file is automatically added to the end. The mode argument is optional,with ‘r’ as default. Modes ‘ r+’, ‘w+’ and ‘ a+’ opens the file for both for updating (note that ‘ w+’ truncates the file).

Windows operating system makes a distinction between text and binary files, so in Windows, ‘b’ appended to the mode opens the file in binary mode, therefore, there are also modes like ‘rb’, ‘wb’,and ‘r+b’.

To understand the various methods which are helpful in reading information from the file, a text file is manually created (having empty line after every text line) having filename list.txt, and kept at path C:/test. The content of the file is:

This is first line.
 This is second line.
 This is third line.
 This is fourth and last line.

Now, open the file using open () function in read mode.

>>> f=open('C:/test/list.txt','r')

Reading file
To read a file’s contents, call read (size) method, which read size bytes of data and returns it as a string, size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; otherwise, at most size bytes are read and returned. If the end of the file has been reached, read () will return an empty string (‘ ‘).

>>> f.read(19)
 'This is first line.'

There is a tell () method, which returns an integer giving the file object’s current position in the file, measured in bytes from the beginning of the file.

>>> f . tell ()
 19L

To change the file object’s position, use seek (of f set, from_what) method. The position is computed from adding offset to a reference point; the reference point is selected by the f rom_what argument. A f rom_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point, f rom_what can be omitted and defaults to 0, using the beginning of the file as the reference point.

>>> f.seek(-52, 2)
 >>> f.read()
 'This is third line.\n\nThis is fourth and last line.'
 >>> f . tell ()
 99L
 >>> f.seek(0,0)
 >>> f.tell()
 0L
 >>> f.read()
 'This is first line.\n\nThis is second line.\n\nThis is third line.\n\nThis is fourth and last line.'

When relevant operations on a file are finished, use close () method to close the file and free-up any system resources taken up by the open file. After calling close (), attempt to use the file object will automatically fail.

>>> f.close()
 >>> f..read()
 Traceback (most recent call last):
 File "<stdin>", line 1, in ?
 ValueError: I/O operation on closed file

There is also a readline () method that read a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file, if the file does not end in a newline. If readline () returns an empty string, the end of the file has been reached, while a blank line is represented by ‘ \n ‘.

>>> f=open('C:/test/list.txt','r')
 >>> f.readline()
 'This is first line.\n'
 >>> f.readline()
 ' \n'
 >>> f.readline()
 'This is second line \n'
 >>> f.readline()
 ' \n'
 >>> f.readline()
 'This is third line.\n'
 >>> f.readline()
 ' \n'
 >>> f.readline()
 'This is fourth and last line.'
 >>> f.readline()
 ' '
 >>> f.close()

For reading lines from a file, one can also loop over the file object.
This is memory efficient, fast, and leads to simple code:

>>> f=open('C:/test/list.txt','r')
 >>> for line in f:
 ... print line,
 This is first line.
 This is second line.
 This is third line.
 This is fourth and last line.
 >>> f.close()

If there is a requirement to read all lines of a file in a list, one can do list (f) or f . readlines ().

>>> f=open('C:/test/list.txt','r')
 >>> list(f)
 ['This is first line.\n', '\n', 'This is second line.\n', '\n', 'This is third line.\n', '\n', 'This is fourth and last line.']
 >>> f.close()
 >>>
 >>> f=open('C:/test/list.txt','r') .
 >>> f.readlines()
 ['This is first line.\n', '\n', 'This is second line.\n', '\n', 'This is third line.\n', '\n', 'This is fourth and last line.']
 >>> f.close()

Writing to a file
Apart from only reading information from a file, there can be a scenario where some data need to be written to a file. To carry out such operation, write (string) method is used, where string argument should be of string data type. Upon success, write () method returns None.

Open “list.txt” and add some text at the end of the file.

>>> f=open('C:/test/list.txt', 'a+')
 >>> f.write('\n\nThis is the new last line.')
 >>> f.seek(0,0)
 >>> f.read()
 'This is first line.\n\nThis is second line.\n\nThis is third line.\n\nThis is fourth and last line.\n\nThis is the new last line.'
 >>> f.close()

File renaming and deletion
Python’s os module provide methods for renaming and deleting files. To rename a file, use rename (src, dst) method, where src argument is source filename, while dst is destination filename.

>>> import os
 >>> os.rename(’C:/test/list.txt’,'C:/test/newlist.txt')

To delete a file, use remove() method.

>>> os.remove('C:/test/newlist.txt')

Python Programming FundamentalsComputer Science