Reading and Writing Files in Python

File handling is taken care of natively by python. The method open() is the single most important method for handling files.

The open() Function

The open function is used for opening or writing into a file in python. Usually we pass two arguments within the open function.

The syntax to open a file object in Python is:

file_object  = open(“filename”, “mode”) 

The first argument in the statement represents the name of the file, whereas the second argument represents the mode in which we are opening the file.The mode tells the interpreter as to which way the file will be used.

Mode


There are for types of modes in python

R - Read mode
w - Write mode
a - Append mode
r+ - Read/write mode

So, let’s take a look at a quick example.

F = open(“workfile”,”w”)
Print F

This snippet opens the file named “workfile” in writing mode so that we can make changes to it. The current information stored within the file is also displayed – or printed – for us to view.

Once this has been done, you can move on to call the objects functions. The two most common functions are read and write.

Create a text file

We can create and manipulate a text file with the following statement

file = open(“testfile.txt”,”w”)

file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)

file.close()

Naturally, if you open the text file – or look at it – using Python you will see only the text we told the interpreter to add.

$ cat testfile.txt
Hello World
This is our new text file
and this is another line.
Why? Because we can.

Reading a Text File in Python

There are multiple ways to read a file in python. We can use the following statement after opening the file as follows.

file.read()

We can pass an integer into the argument of the read() method to return a set of characters as shown below

file = open(“testfile.txt”, “r”)

print file.read(5)

file = open(“testfile.txt”, “r”)

We can also use the readline() method which returns the line in the response. We need to repeatedly call this method to get the line we are looking for

print file.readline()

output:

Hello World

We can also pass the an integer as the argument for the readline method to return a specific line that we need.

Looping in a file object

When we want to read/return all the lines present in the text file, looping is one of the most efficient ways to achieve it.

file = open(“testfile.txt”, “r”)
print file.readline(3)

But what if we wanted to return every line in the file, properly separated? You would use the same function, only in a new form. This is called the file.readlines() function.

file = open(“testfile.txt”, “r”)
print file.readlines()

The output you would get from this is:

[‘Hello World’, ‘This is our new text file’, ‘and this is another line.’, ‘Why? Because we can.’]

Looping over a file object

When you want to read – or return – all the lines from a file in a more memory efficient, and fast manner, you can use the loop over method. The advantage to using this method is that the related code is both simple and easy to read.

file = open(“testfile.txt”, “r”)
for line in file:
print line,

This will return:

Hello World
This is our new text file
and this is another line.
Why? Because we can.

Using the File Write Method


We can write into a file using file.write() method after opening the file in write mode.

file = open(“testfile.txt”, “w”)

file.write(“This is a test”)
file.write(“To add more lines.”)

file.close()

Obviously, this will amend our current file to include the two new lines of text. There’s no need to show output.

Closing a File


We can use the command file.close to close the file and free up the memory for other things.

Note: A file can be closed only once