Reading and Writing Files in Python

We offer you a brighter future with FREE online courses - Start Now!!

Our programs were working fine till now. We prompted the user to input some data. We then processed that data in our program and then printed some output on the screen. Then why did we need to bring files into the picture?

This is because, while making real applications we will need to store user’s data into these files. We will also need our program to retrieve data from files.

So before we write programs with real applications, we need to learn how to write programs that can read and write into simple text files.

Opening a file in Python

No matter which programming language we use, the simplest way of storing our data is by writing them into text files. But how do we access a file through our Python program? We do this by creating a file object ( or file stream).

Our program can then call the methods, which manipulate data in the file, on this file object. Python provides us with a simple function open() which opens a file and returns a file object for that file.

How to open File in Python Syntax:

open(filename, access_mode)

We call the open function on a file avengers.txt.

Code:

f = open('avengers.txt')

The default access_mode is the read mode “r”. If open() successfully opens the file, the interpreter returns a file object. This file object gets assigned to the variable f, as per our code.

Access modes in Python

Access mode specifies the mode in which we want to open our file. This can be “r” for reading, “w” for writing, or “a” for appending.

  • ‘r’ – Opens a file in reading mode. It is the default mode. If the file doesn’t exist, it raises
    an error.
  • ‘w’ – Opens a file in write mode. It overwrites the contents of the file. If the file doesn’t
    exist, it creates a new file and writes into it.
  • ‘a’ – Opens a file in append mode. Creates a new file if the file doesn’t exist. Adds new
    data to the end of the file if the file already exists.

You can add a ‘+’ to the end of the mode, which specifies the reading as well as writing mode. You can add “b” to the end of any of these modes to specify opening a binary file.

Closing a file in Python

Once we finish processing the open file in our program, we can close the file. This frees up the resources tied up with the file. Moreover, it prevents data loss. So, a good programmer should always remember to close a file.

We simply call the close method on the file object to close the file.

Code:

f.close()

Do you have a terrible memory like me? And you know you’re gonna end up not closing the file once you’re done working with it? Well, Python has you covered. We can use the with statement. So all you need to do is use with and open together.

Now the interpreter will automatically call the close function once you’re done processing the file’s contents.

Code:

with open(“avengers.txt”) as f:
    # to do

Also, there might be times when open() cannot successfully open a file and the code terminates its execution without closing the file. Or a potential error might occur while manipulating the contents of the file. So, to leave no loopholes, we use the try…finally block while opening and closing a file.

Code:

try:
    f = open(‘Avengers.txt’)
    # to-do
finally:
    f.close()

Now we are sure that the file will close eventually even in case of an exception.

Reading from a file in Python

For reading from a file, you first need to open that file in the read mode, “r”. Let’s go ahead in the Python shell and do this:

f = open('avengers.txt', 'r')

Let’s look at all the different ways in which you can read contents from a file.

1. Looping over the file in Python

You can use the for loop to read individual lines from the file.

Code:

for line in f:
    print(line)

Output:

1. Iron man2. Captain America

3. Black Widow

4. Hulk

5. Thor

6. Hawk-eye

>>>

2. read(size) in Python

This function lets you read size number of bytes from the file. This argument is optional and the function reads the entire file if we pass no argument.

Look at this short session of Python shell:

f.read(11)
'1. Iron man'
f.read()
'\n2. Captain America\n3. Black Widow\n4. Hulk\n5. Thor\n6. Hawk-eye\n'

The first call to read reads 11 bytes and the second call reads the rest of the file as we passed no argument.

3. readline(size) in Python

This function lets you read size bytes of a line. If we pass no argument, it reads the entire line. Observe the example below:

f.readline(4)
'1. I'
f.readline()
'ron man\n'
f.readline()
'2. Captain America\n'
f.readline()
'3. Black Widow\n'

Note that readline() reads a new line every time it gets called.

4. readlines() in Python

This reads the entire contents of the file and returns a list of all the lines.
Code:

f.readlines()

Ouput:
[‘1. Iron man\n’, ‘2. Captain America\n’, ‘3. Black Widow\n’, ‘4. Hulk\n’, ‘5. Thor\n’, ‘6. Hawk-eye\n’]

Writing into a file in Python

In Python writing into a file is as easy and convenient as reading from it. To write into a file in Python, we first need to open it in write mode, i.e, “w” or append mode, “a”.

You can then write into your file using either of the methods given below:

1. write(string) in Python

This method takes a string as an argument and writes this string into the file. Be sure to append a newline character, “\n”, to the string if you want to specify a line ending.

f = open("myfile.txt", "w")
f.write("Hey there from PythonGeeks\n")
27
f.write("Adding line 2\n")
14

2. writelines(list_of_strings) in Python

This method takes a list of strings and writes all those strings to the file. Make sure you add appropriate line endings.

f.writelines(["This is line 3\n", "This is the last line\n"])
f.close()

The changes are finally committed to the file once you close it.

Output

Hey there from PythonGeeksAdding line 2

This is line 3

This is the last line

Summary

We have learned all about reading and writing files in Python. You can use this to build more dynamic programs. Since file handling is a very important part of programming, we advise you to go ahead and experiment with these methods in your own Python shell.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *