Python

How To Read and Write Files Using Python.

Reading and writing to files using Python is easy to do. In this post, I will go over how to read and write to text files.

First, create a file object by calling the open function.

file_object = open('test.txt', 'r')
data = file_object.read()
print(data)
file_object.close()

Python’s built-in open function is used to open test.txt file in read mode.  This tells python what file to open and the mode to open it in.  In this case the mode is read only.  It is not possible to write or save data to a read-only file.  The file contents are read as a string into the data variable and printed.  After we are done working with the file, it is closed.  Closing files is good practice, it frees up memory and allows other programs to access the same file.

The example above reads the file’s entire contents into a variable.  This is not always what we want to do.  It is possible to tell Python to read a file one line at a time, read all the lines or read the file in chunks.  Reading the file in chunks is handy when you’re dealing with streaming data or large files that would quickly fill up the computer’s memory.

file_object = open('test.txt', 'r')
data = file_object.readline()  # read just one line
print(data)
file_object.close()

Running the example above will read only one line from the test.txt file.

file_object = open('test.txt', 'r')
data = file_object.readlines()  # read all the lines
print(data)
file_object.close()

Running the above will read all the lines in the text file.  The difference between the read() and readlines() methods is in the return type. read() returns the file’s contents as a single string whereas readlines returns a list.

To read a file in chunks we use a loop:

file_object = open('test.txt', 'r')

while True:
    data = file_object.read(1024)
    print(data)
    if not data:
        break

The code above makes use of a while loop to read 1 Kilobyte of data on each iteration.  The size of the chunk to be read can be set by the programmer to any value you like.  If there’s nothing left to read, the loop exits.

Writing Files

Writing to files is similar to reading them, first you create a file object, open the file in write mode, write data to it and close the file after you’re done with it.

file_object = open('test.txt', 'w')
data = "This is sample data that will be saved to a file"
file_object.write(data)
file_object.close()

A more Pythonic way to handle files

Python has a builtin function called with that can will automatically close files you open.  To use the with place any code to open a file within the with code block.

with open('test.txt', 'r') as file_object:
    for line in file_object:
        print line

Using with when opening files will always make sure that your files are closed when you’re done with them.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s