Open a Text File

You can open up text files quite easily in Python. Just use the inbuilt open function. In between round brackets, you type the name and path of the file you want to open:

r"C:\Users\Ken\Documents\test.txt"

openFileFromPath = open( fileToOpen )

Here, we've hard-coded a file name and path (Windows machine). Note how we use a lowercase 'r' before the file name and its quote marks. This was explained in an earlier lesson and is short for raw. You can also use a file path with escape characters:

fileToOpen = "C:\\Users\\Ken\\Documents\\test.txt"

If we didn't use the backslash escape character it would be just this, which is the usual file path on Windows:

fileToOpen = "C:\Users\Ken\Documents\test.txt"

The above line would give us errors, however.

Once you have a file and a path, place it between the round brackets of open. Because it's on the right of an equals sign, a file object will be created in our variable called openFileFromPath.

Creating a file object allows you to call the file functions:

read
readline
readlines
write
close

So you would do this:

openFileFromPath.read()
openFileFromPath.write("Some text")
openFileFromPath.close()

One important parameter that's used with the open function is mode. Files can be opened in read mode (r), write mode (w), append mode (a), and read and write mode (r+). Each mode is shortened to a single letter and goes as a parameter to open:

open( fileToOpen, 'r')
open( fileToOpen, 'w')
open( fileToOpen, 'a')
open( fileToOpen, 'r+')

The default is read mode. So if you only want to read the file into a text area then you can miss out the 'r' for the first one.

open( fileToOpen)

Let's adapt our open file function from the previous lesson so that it reads a text file into the text area on our form. At the moment, your open file function should look like this:

Dialog box in TKinter and Pytho to select a file to open

If you select a file from the dialog box its name and path appear in the variable we've called filename. We can use this variable in the open function. We could just do this:

the_file = open(filename)

We'd then create a file object called the_file. However, it's best to use a bit of error checking when you're opening files. You can use a try … except block.

try:

# OPEN FILE HERE

except IOError:

# SOMETHING WENT WRONG

else:

# SOMETHING ELSE WENT WRONG

The type of error to check for when you're dealing with files for is usually the IOERROR. For example, if the file doesn't exist Python will throw an IOERROR. The code for the except part of the statement will then execute and your program won't crash.

You can use an if statement instead of a try statement. If a file has been opened successfully then a value of true can be tested for. You can test for a value of false, if the file hasn't been opened successfully, or if the cancel button was clicked:

if filename:

# CODE HERE

elif filename == '':

# SOMETHING WENT WRONG

Notice the elif part:

elif filename == '':

You can test for a blank string, if you want. This is just the same as testing for false. Or you could use the not keyword:

elif not filename:

In our code, we'll combine a try block and an if statement.

try:

if filename:

# OPEN FILE HERE

elif filename == '':

# ERROR MESSAGE HERE

except IOError:

# ANOTHER ERROR MESSAGE HERE

As the code for the if part, we can have this:

if filename:

the_file = open(filename)
textArea.insert(tk.END, the_file.read())

elif not filename:

messagebox.showinfo("Cancel", "You clicked Cancel")

First, we're opening up a text file in read mode:

the_file = open(filename)

Next, we're inserting the text file into the text area:

textArea.insert( tk.END, the_file.read() )

The text file itself is in our file object, which we called the_file. We're using the read function to get the whole contents of the file. We're then inserting it into the text area.

One other thing you may have noticed is that we're using a message box. This will display if the user cancelled. Remember, you need the following line at the top of your code to use message boxes:

from tkinter import messagebox

The if statement goes in the try part of a try … except block:

try:

if filename:

the_file = open(filename)
textArea.insert(tk.END, the_file.read())

elif not filename:

messagebox.showinfo("Cancel", "You clicked Cancel")

except IOError:

messagebox.showinfo("Error", "Could not open file")

Add that to your code, inside of your openfile function, and just below the line that displays the dialog box.

Add one more line to close the file:

the_file = open(filename)
textArea.insert(tk.END, the_file.read())
the_file.close()

But top part of your code should look like this:

Python code to open a text file

You can try it out now. Click your File menu and then Open. When you get the open file dialog, click the Cancel button. You should see your message box appear, the one with "You clicked Cancel" in it. Open up a text file on your system.

Now open up a text file. You should find that it appears in your text area. Here's ours:

A text file read into a Tkinter text widget

If you haven't got a suitable text file, or just want to use the same one as in these tutorials, then you can download it here:

POSTCODE TEXT FILE

Notice that the default text we had is still there. The text area hasn't been cleared before the new contents appear. To clear a text area, the code is this:

textArea.delete('1.0', tk.END)

The function to use on your text area is delete. In between the round brackets of delete, we have a line and character number pointing to the start of the text area, and the inbuilt constant tk.END, which takes you to the end of the text area.

Place the line just after the line that opens the text file:

the_file = open(filename)
textArea.delete('1.0', tk.END)
textArea.insert(tk.END, the_file.read())
the_file.close()

Run your program again and you should find that the default text gets cleared.

One thing you will have noticed is that it's hard to scroll down the page. It's hard because there are no scroll bars. Let's add some to our text area.

In the next lesson, we'll add some scrollbars to our text area.

Text Area Scrollbars >