1 of 25

Dr. Harpreet Singh

Head, PG Department of Bioinformatics,

Hans Raj Mahila Maha Vidyalaya,

Jalandhar, Punjab, India

e-module

File Handling in Python: Reading/Writing data to/from files

2 of 25

Methods of input data

  1. Reading data statically using a variable
  2. Reading data dynamically from the user with the help of input() method
  3. Reading data from files using the concept of File handling

3 of 25

Why Reading from files?

  1. Huge amount of data difficult to feed in to the program
  2. Saves time and energy.
  3. Avoid errors while data input using standard methods.
  4. Allows dynamic data inputs.

5. Makes the program more flexible.

6. Mostly, in programming languages, all the values or data are stored in some variables which are volatile in nature.

7. Because data will be stored into those variables during run-time only and will be lost once the program execution is completed.

4 of 25

Types Of File in Python�

  • There are two types of files in Python and each of them are explained below in detail with examples for your easy understanding.

They are:�

  • Binary file
  • Text file

5 of 25

Binary Files

Most of the files that we see in our computer system are called binary files.

Example:

  • Document files: .pdf, .doc, .xls etc.
  • Image files: .png, .jpg, .gif, .bmp etc.
  • Video files: .mp4, .3gp, .mkv, .avi etc.
  • Audio files: .mp3, .wav, .mka, .aac etc.
  • Database files: .mdb, .accde, .frm, .sqlite etc.
  • Archive files: .zip, .rar, .iso, .7z etc.
  • Executable files: .exe, .dll, .class etc.

  • All binary files follow a specific format. We can open some binary files in the normal text editor but we can’t read the content present inside the file. That’s because all the binary files will be encoded in the binary format, which can be understood only by a computer or machine.
  • For handling such binary files we need a specific type of software to open it.

For Example, You need Microsoft word software to open .doc binary files. Likewise, you need a pdf reader software to open .pdf binary files and you need a photo editor software to read the image files and so on.

6 of 25

Text Files�

Text files don’t have any specific encoding and it can be opened in normal text editor itself.

Example:

  • Web standards: html, XML, CSS, JSON etc.
  • Source code: c, app, js, py, java etc.
  • Documents: txt, tex, RTF etc.
  • Tabular data: csv, tsv etc.
  • Configuration: ini, cfg, reg etc.

7 of 25

Reading a file is a three-step process in Python:

  1. Open the file
  2. Read the file
  3. Close the file

8 of 25

Step1: Open the file

  • There is a built-in function called open that creates a file han-dle. This filehandle is used to refer to the file during the file’s lifetime.
  • The open function takes two parameters:-

name of the file and opening mode

The file name is a string with the file name, in most cases including the system path. When the system path is included, this absolute path is used by the program. In case you enter just the file name (without any path), a relative path is assumed

9 of 25

Step1: Open the file

  • The second parameter has the following valid parameters:

“r” to read

“w” to write

“a” to append data at the end of a file.

“r+” to Read or Write

“a+” to Append or Read

  • The default value is “r.”

Note: The above-mentioned modes are for opening, reading or writing text files only.

While using binary files, we have to use the same modes with the letter ‘b’ at the end. So that Python can understand that we are interacting with binary files.

For example “wb” – Open a file for write only mode in the binary format.

10 of 25

Step1: Open the file

Using open create a file handle to read a file:

Example 1:

>>> file_handle = open(’readme.txt’, ’r’)

In the above example, we are opening the file named ‘’readme.txt’, present at the current location.

Example 2:

>>> file_handle = open(“C:/Documents/Python/test.txt”, “r+”)

In the above example, we are opening the file named ‘test.txt’ present at the location ‘C:/Documents/Python/’ and we are opening the same file in a read-write mode which gives us more flexibility.

Example 3:

>>> file_handle = open(“C:/Documents/Python/img.bmp”, “rb+”)

In the above example, we are opening the file named ‘img.bmp’ present at the location “C:/Documents/Python/”, But, here we are trying to open the binary file.

Note: - file_handle is not the file, but a reference to it.

11 of 25

Step2: Reading the file

Once the file is opened, we can read its contents. The file handle has several methods to read a file; here are the most used:

  • read(n): Reads n bytes from the file. Without parameters, it reads the whole file.
  • readline(): Returns a string with only one line from the file, including ’\n’ as an end of line marker. When it reaches the end of the file, it returns an empty string.
  • readlines(): Returns a list where each element is a string with a line from the file.

12 of 25

Step2: Reading the file: Sample File

Now let’s observe what each read method does:

Let’s create a sample text file named test1.txt as shown below.

13 of 25

Step2: Reading the file: Examples

>>> my_file = open(“D:/test1.txt”, “r”)

>>> print(my_file.read(5))

Output:

>>> Hello

Here we are opening the file test.txt in a read-only mode and are reading only the first 5 characters of the file using the my_file.read(5) method.

Example 1:

14 of 25

Step2: Reading the file: Examples

>>> my_file = open(“D:/test1.txt”, “r”)

>>> print(my_file.read())

Output:

Hello World

Hello Bioinformatics

Hello Python

Here we have not provided any argument inside the read() function. Hence it will read all the content present inside the file.

Example 2:

15 of 25

Step2: Reading the file: Examples

>>> my_file = open(“D:/test1.txt”, “r”)

>>> print(my_file.readline())

Output:

Hello World

Using this function we can read the content of the file on a line by line basis.

Example 3:

16 of 25

Step2: Reading the file: Examples

>>> my_file = open(“D:/test1.txt”, “r”)

>>> print(my_file.readlines())

Output:

['Hello World\n', 'Hello Bioinformatics\n', 'Hello Python']

Here we are reading all the lines present inside the text file including the newline characters.

Example 4:

17 of 25

Step2: Reading the file: Examples

>>> filename = “C:/Documents/Python/test.txt”

>>> filehandle = open(filename, ‘r’)

>>> filedata = filehandle.read()

>>> print(filedata)

Output:

Hello World

Hello Bioinformatics

Hello Python

Here we are reading all the lines present inside the text file including the newline characters.

Example 5: Reading the entire file at once

18 of 25

Writing to the file

  • In order to write data into a file, we must open the file in write mode.
  • We need to be very careful while writing data into the file as it overwrites the content present inside the file that you are writing, and all the previous data will be erased.

We have two methods for writing data into a file as shown below.�

  • write(string)
  • writelines(list)

19 of 25

Writing to the file

Example 1:

>>> my_file = open(“D:/test.txt”, “w”)

>>> my_file.write(“Hello World”)

The above code writes the String ‘Hello World’ into the ‘test.txt’ file.

20 of 25

Writing to the file

Example 2:

>>> my_file = open(“D:/test.txt”, “w”)

>>> my_file.write(“Hello World\n”)

>>> my_file.write(“Hello Python”)

  • The first line will be ‘Hello World’ and as we have mentioned \n character, the cursor will move to the next line of the file and then write ‘Hello Python’.
  • Remember if we don’t mention \n character, then the data will be written continuously in the text file like ‘Hello WorldHelloPython’

21 of 25

Writing to the file

Example 3:

>>> fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]

>>> my_file = open(“D:/test.txt”, “w”)

>>> my_file.writelines(fruits)

The above code writes a list of data into the ‘test.txt’ file simultaneously.

22 of 25

Writing to the file: Append Mode

Example 4:

>>> my_file = open(“D:/test.txt”, “a+”)

>>> my_file.write (“Strawberry”)

>>> my_file.write (“\nGuava”)

The above code writes a list of data into the ‘test.txt’ file simultaneously

To append data into a file we must open the file in ‘a+’ mode so that we will have access to both the append as well as read modes.

23 of 25

Step3: Closing the file

  • In order to close a file, we must first open the file. In python, we have an in-built method called close() to close the file which is opened.

  • Whenever you open a file, it is important to close it, especially, with write method. Because if we don’t call the close function after the write method then whatever data we have written to a file will not be saved into the file.

Example:

>>> my_file = open(“D:/test1.txt”, “r”)

>>> print(my_file.read())

>>> my_file.close()

24 of 25

References

  • Bassi, S. (2016). Python for bioinformatics. Chapman and Hall/CRC.
  • Model, M. L. (2009). Bioinformatics Programming Using Python: Practical Programming for Biological Data. " O'Reilly Media, Inc.".
  • https://www.softwaretestinghelp.com/python/python-file-reading-writing/

25 of 25

Thanks