Reading and Writing Text to Files

Overview

Being able to interact with other files on the system is important to allow you to create more meaningful and powerful programs.

Keywords

file1 = open([path],[state]) - This opens a file that is located at the path stated, this is assigned to the object called file1 in this case. Python allows a range of states to open a file.
"r" - Read
"w" - Write
"a" - Append
"r+" reading and writing
Note this is assigned "r" by default.
Once a file is open there are a range of options available.
file1.write() - this will write to the file
file1.read() - the returns the entire file
file1.readline() - this will return the file line by line. This allows large files to be open and read without loading the entire file to memory.
file1.close() - this method requires no parameters and closes the file, this is an important step as if you have been writing to a file, this may not complete as expected if you fail this step
file1.closed - This returns a Boolean True or False depending on if the file has been closed.

Example Reading

Here we are going to read a file into a variable, then return the contents to the console.
file1 = open("names.txt","r")
names = file1.read()
print (names)
file1.close()
Note we don't need the entire path if the file is in the same location as the python file.
The text file will cotain a list of 3 names, Dean, Ryan, Owen all on spate lines.
This returns:
Dean
Ryan
Owen

Example Appending

Ok then add a name to the list.
file1 = open("names.txt","a")
file1.write("Em")
file1.close()

file1 = open("names.txt","r")
names = file1.read()
print (names)
file1.close()
This returns:
Dean
Ryan
Owen
Em

Example Writing

If this file didn't exist or we want to write over this file, then we can use the write option.
file1 = open("names.txt","w")
file1.write("Craig")
file1.write("Dawn")
file1.close()

file1 = open("names.txt","r")
names = file1.read()
print (names)
file1.close()
This returns:
CraigDawn
This is added the strings to the file, though it has not done this on a new line, we need to add "\n" at the end of each name if we want them on new lines.

Example Reading with a Loop

We can use loops to write to a file, and also to read a file line by line. This is a very efficient way to read a large file due to the way python only reads the file line by line and does not load the entire file in memory.
file1 = open("names.txt","w")
for x in range(5):
    file1.write(str(x)+"\n")
file1.close()

file1 = open("names.txt","r")
for line in file1:
    print (line.replace("\n",""))
file1.close()
This returns:
0
1
2
3
4

Example using a With Statement

It is a good idea to open a file with a with statement as this will ensure that the file is closed.
with open("names.txt","w") as file1:
    for x in range(5):
        file1.write(str(x)+"\n")

with open("names.txt","r") as file1:
    for line in file1:
        print (line.replace("\n",""))
This returns:
0
1
2
3
4

Which is the same result as the example above, but this method will close the file even if an exception is raised.



Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.


Related Pages

Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.
Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter - Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines