Introduction

Note: This tutorial assumes a basic knowledge of Python syntax.

In this tutorial you will learn how to read and write basic text files in Python.

Opening A File

To open a file, we use the open() function to create a file object. Open takes two arguments: the name of the file and the mode for which we'd like to open the file.

A file can be opened for reading ("r") or writing ("w"), just as with most other languages. Let's open up a file for reading:

filename = "myfile.txt"
file = open(filename, "r")

Reading From A File

Now that we've opened out file, let's read in the entire contents of the file and print them on standard output:

contents = file.read()
print contents

We can also choose to read in the file as a list of lines, if we so desire:

lines = file.readlines()
for line in lines:
    print line

Closing The File

We must close the file with close() once we are finished using it, otherwise other applications will not be able to access it. Python will automatically close the file when the script finishes executing, but its good practice to always explicitly close files:

file.close()

Writing To A File

Writing to a file is just as simple as reading from it. Let's open a file, this time for writing ("w"), and write some text to it. If the file does not exist, it will be created:

filename = "anotherfile.txt"
file = open(filename, "w")
file.write("Forks and spoons are obviously inferior.")
file.close()

We can also write a list of lines to the file, just as we were able to read in a list of lines:

lines = ["a line of text", "another line of text", "a third line"]
file.writelines(lines)
 
# or, alternatively:
 
for line in lines:
    file.writeline(line)
 
file.close()

Appending To An Existing File

When we open a file in write mode ("w"), any contents of that file will be replaced by whatever we write to it. But in many cases, we simply want to add (append) to the existing contents of a file.

To append to an existing file, simply open the file in append mode ("a"):

file = open(filename, "a")
file.write("some appended text")
file.close()

Conclusion

You should now know how to do basic text file I/O in Python. You can consult the Python documentation for file objects for more information on the different methods available.

I always welcome questions or feedback about this tutorial. Simply post a reply or PM me; I'm glad to help!

This page was published on It was last revised on

Contributing Authors

0

0 Comments

  • Votes
  • Oldest
  • Latest