Python File Operations


In this section we will demonstrate file operations in Python; we will learn how to open and how to write into a file and how to read the file.

A file can be defined as the named memory location that is used to store the information. A file is used to store the data on the non volatile memory that is hard disk permanently.

RAM, the random access memory, is not used for this purpose because RAM is a volatile memory and loses all its data when the power is cut off or the computer is shut down. All the data will be lost.

A file is opened first, when if the user wants to write on it or read the data from it. After the user is done with r=writing or reading the data from the file, the file is closed. The file operation takes place in Python by the following sequence:

  1. Opening a file
  2. Reading or writing on the file
  3. Closing the file

 

Opening a File

A file in Python programming can be opened by using the built in open () function. The open () function is used to return an object of the file which can also be called as handle, the handle is used to read and modify the file.

Consider the following example:

f = open (“exp.txt”)

This command will open the already existing file named exp in the memory. In Python we can also specify that in which mode the file should be opened for example if we want to read the file then we will open it in read mode by using ‘r’, and if we want to write on the file or append then we will open the file in write mode by using ‘w’ or ‘a’. There is also a feature in Python that we can choose to open a specific file in binary mode or in the text mode.

If the binary and text modes are not specified then the file will be opened in the text mode by default. We get strings when we are reading the file in the text mode. But the binary mode returns bytes. If the user wants to deal with the images or exe files then he should open the file in binary mode.

Consider the following table in which Python file modes are described:

Modes Description
‘r’ This mode is used to open the file for reading. If no mode is specified the file will be automatically opened in the reading mode.
‘w’ This mode is used to open the file to write on a file. If the file does not already exist in the memory then a new file is created. If the file already exists then it will truncate the file.
‘x’ This mode is used to open a file for exclusive creation; if the file is already existed then this operation will be failed.
‘a’ This mode is used to open the file in the append mode. If the file already exists then file will be opened for appending then file will be appended at the end without truncation.
‘t’ This mode is used to open the file in the text mode. If no mode is specified the file will be automatically opened in the text mode.
‘b’ This mode is used to open the file in the binary mode.
‘+’ This mode is used to open the file in updating mode that is we can read the file and at the same time we can write on it.

In the other languages the character ‘a’ was equal to 97 in the ASCII code but in Python it will not imply until the character itself is encoded using the ASCII code. Therefore, to open a file in append mode that is ‘a’, you should use the correct encoding to avoid unexpected results; the file to be opened in the text mode should be opened by the following command:

f = open (“exp.txt”, mode = ‘r’, encoding = ‘utf-8’)

 

Closing a file

When the operations are performed on the file the file should be closed. File closing is important because when we close a file all the resources will be freed up that were tied with the file.

A file is closed by Python itself as the Python has a garbage collector, but we should properly close the file. An opened file in Python can be closed by the following command:

CODE

f = open (“exp.txt”, encoding = ‘Utf-8’)

  1. close ()

Closing the file in this may be not much safer that is an exception can be occurred while performing some operations on the file. You should use try…finally block instead to close a file safely. Consider the following example:

try:

    f = open (“exp.txt”, encoding = ‘Utf-8’)

finally:

  1. close ()

In this way the file will be closed even if there are some exceptions while performing operations on the file. The flow of program will be stopped in this way.

 

Writing to a file

We can only write in a file when the file is opened therefore, to write on a file you first have to open the file using the ‘w’ mode or ‘a’ mode or the ‘+’ mode. If we are using the ‘w’ mode then we should be aware that this will overwrite on to the file if the file you tried to open the file which already exists. All the data stored in the file will be deleted if the file is opened in the ‘w’ mode.

In a file to write strings or bytes the write () function is used. The write () method is used to return the number of characters that are written into a file.

Consider the following example in which we have opened a file in ‘w’ mode if the file does not exist, a new file will be created and the data that we will write will be written on the new file:

CODE

>>> with open(“exp.txt”, ‘w’, encoding = ‘utf-8’) as f:

          f.write(“First file in Python”)

OUTPUT

20

20

The above lines of code will write “First file in Python” on the file named exp. The output of this code will be the number that is returned by the write () function after counting the number of characters in the string that was written on the file.

If there are multiple lines to be written in the file then we should use the escape sequence to generate a new line that is \n.

 

Reading from a File

The content in the file can be read when we open the file in the reading mode. A file can be opened in Python in reading mode by using different ways that is we can use the built in function read (size) method to read in size the number of data. If the parameter size in the method read (size) is not defined then the method will read the data up to the end of the file.

CODE

>>> with open(“exp.txt”, ‘w’, encoding = ‘utf-8’) as f:

          f.write(“First file in Python”)

>>> f = open(“exp.txt”, ‘r’, encoding = ‘utf-8’)

>>> f.read(3)

>>> f.read(4)

>>> f.read(8)

>>> f.read(9)

>>> f.read(2)

OUTPUT

20

‘Fir’

‘st f’

‘ile in P’

‘ython’

first-file-in-python

In the above example we have opened the file exp in writing mode and wrote “First file in Python”, the number of characters written in the file are returned. Then again we opened the file in the reading mode. When the read function is used we passed argument 3 and first 3 characters of the text in the file are printed and so on. When we reach the end of the file the read function returned an empty string.

In Python while reading the file we can change the position of the cursor to print the characters that we want using the ‘seek ()’ function. There is another function ‘tell ()’ that tells the user the current position of the cursor.

We can also read the file in Python line by line by using the ‘for statement’. In this way we can save a lot of time. The ‘readline ()’ function is used to read an individual line from the file.

 

Python File Methods

Consider the following table, in which the Python file methods are described:

Methods Description
close () This method is used to close a file.
detach () This method is used to separate the underlying binary buffer from the TEXTIOBASE and then return it.
fileno () This method is used to return the integer number of the file.
flush () This method is used to flush the write buffer that is of the file stream.
isatty () This method is used to check the file stream, if the file stream is interactive then it returns true.
read (n) This method is used to read n characters from the file and return it.
readable () This method is used to check the file stream if the file stream is readable then it returns true.
readlines (n=-1) This method is used to read and then return one line from the file. It can read up to n number of lines.
seek (offset, from= SEEK_SET) This method is used to change the position of file to offset in bytes.
seekable () This method is used to check the file stream if the file stream supports random access then it returns true.
tell () This method is used to return the current location of the file.
truncate (size = None) This method is used to resize the file stream.
writable () This method is used to check file stream if the file can be written on then it returns true.
write (s) This method is used to write the string to the file. This method also returns the number of characters in the file.
writelines (lines) This method is used to write a number of lines to the file.