How to read a text file using Python Tkinter

In this Python tutorial, we will learn how to work with the files in Python Tkinter. We will read a Text File using Python Tkinter and also we will cover these topics.

  • Python Tkinter read text file
  • How to Open Text File in Python Tkinter
  • How to Read Text File in Python Tkinter
  • How to Display Text File in Python Tkinter
  • How to Save to Text File in Python Tkinter
  • How to write Text File in Python Tkinter
  • How to Edit Text File in Python Tkinter
  • How to Create Text File in Python Tkinter
  • How to Close Text File in Python Tkinter

Python Tkinter Open Text File

  • In this section, we will learn how to open a text file using Python Tkinter that are present in your system.
  • open() function is used to open files.
  • There are mainly three modes of opening files in Python Tkinter.
    • r ‘: open file in read-only mode.
    • w‘: Open file in write-only mode.
    • a‘: Open fil in append mode.
  • read mode is the default mode. That means even if the read mode is not specified while opening the file it will use it.
  • As in our system, we see a file dialog appears to open a file similar thing we will do using Python Tkinter.
  • Python Tkinter has a module named filedialog using which we can open system files.
  • Let’s see the implementation of Python Tkinter Read a Text File

Syntax:

Here is the syntax for using open() function

f = open("file_path", "mode")
data = f.read()
  • Here, file_path refers to the file location & we will be using filedialog to do so.
  • mode could be ‘r’, ‘w’, ‘a’. Any mode having suffix ‘+’ will perform both read & write.
  • Here, f is a file pointer and data holds the content in the text file.

Here is the Syntax for using filedialog in Python Tkinter.

from tkinter import filedialog

tf = filedialog.askopenfilename(
        initialdir="C:/Users/MainFrame/Desktop/", 
        title="Open Text file", 
        filetypes=(("Text Files", "*.txt"),)
        )
  • to access filedialog, we need to import the module.
  • tf is the variable that will represent filedialog.
  • in the filedisalog class we are using asopenfilename function.
  • initialdir is the default directory that will open in filedialog.
  • title is the header of the filedialog box
  • filetypes specifies types of files you want to accept. It works as a filter. Our our case we have specified that we want to files only with .txt extension.
  • "*.txt" here * means any file irrespective of name but must have txt extension.

Let’s see a small program to understand what we have learned so far.

You may like Python catch multiple exceptions and Python Exceptions Handling.

Code:

In this code, we have used the open function to read the file content in Python tkinter. The content is displayed in the Text widget. Text files can be selected using the filedialog box. The selected file path is displayed in the entry box.

from tkinter import *
from tkinter import filedialog

def openFile():
    tf = filedialog.askopenfilename(
        initialdir="C:/Users/MainFrame/Desktop/", 
        title="Open Text file", 
        filetypes=(("Text Files", "*.txt"),)
        )
    pathh.insert(END, tf)
    tf = open(tf)  # or tf = open(tf, 'r')
    data = tf.read()
    txtarea.insert(END, data)
    tf.close()

ws = Tk()
ws.title("PythonGuides")
ws.geometry("400x450")
ws['bg']='#fb0'

txtarea = Text(ws, width=40, height=20)
txtarea.pack(pady=20)

pathh = Entry(ws)
pathh.pack(side=LEFT, expand=True, fill=X, padx=20)



Button(
    ws, 
    text="Open File", 
    command=openFile
    ).pack(side=RIGHT, expand=True, fill=X, padx=20)


ws.mainloop()

Output:

In this output, we have selected a text file named Readme.txt. You can see the content of Readme.txt is displayed on the screen.

python tkinter open file

Python Tkinter Read Text File

  • In this section, we will learn how to Read text file using Python Tkinter.
  • Most of the part is already covered in a previous section. So here we will discuss things that are not covered in the previous section.
  • We will talk about read(), readline(), readlines(), readable()
  • read() is used to read the entire content of the file.
  • readline() returns the content in the line only
  • readlines() returns all the content of the file in the list form. each line is separated.
  • readable() checks if the file content is in human-readable form. It returns a boolean.
  • To support our example we have created a text file read.txt
python tkinter read text file samplefile.
python tkinter read text file

The text mentioned in the above image is a dummy text Now we will perform read functions using this read.txt file.

read():

To read the file and print entire data we use read() function.

f = open("read.txt")
print(f.read())

This code will return the entire content of the read.txt file.

If we pass integer argument to this read() function then it will return words till that number. Let’s say if it is print(f.read(5)) then the output will be One m that is the first five characters including space. and we run the print(f.read()) function again then it will display the remaining content. This may be a little confusing, but this example will clear it all.

f = open("read.txt")
print(f.read(5))
print(f.read())
python tkinter read text file sample file
python tkinter read text file

In this output, you can observe that when we have called read() function again that it has continued where it left in the first line.

readline():

  • This function returns the line of the content. Every time the program is run it returns the next line
  • Since this text file has 4 lines, so we need to implement this function 4 times to see all the lines on the screen.
  • Like read() function, readline() also return the consecutive characters tilll the passed integer value.
  • Let’s see everything that we have learned in action.
f = open("read.txt")
print(f.readline(5)) # 1
print(f.readline())  # 2
print(f.readline())  # 3
python tkinter read text file using readline
python tkinter read text file

In this output, you see that in the second line of code we have passed argument 5 as result in the output only One m is printed. In the second line of code, we have again printed the read.txt using readline() function. This has continued the text and printed a line only. So you can see each the value of the function is printed it prints just one line of the text file. In total 3 times, the value of readline() function is printed.

readlines():

  • readlines() function appends each line into a list and then returns it. In other words, the output of this function is a list with content lines as list items.
  • This is very useful if you want to target a specific line in the table.
  • No matter what integer argument you pass it will only return the line on index 0. But if you pass 0 then it will return the entire list.
  • Let’s see everything that we have learned in action.
f = open("read.txt")
print(f.readlines(2))
print(f.readlines())
print(f.readlines())
python tkinter read text file readlines
python tkinter read text file

In this output, you can see that with readlines() is provided with argument i.e 2 even then it displays the first. Also, you can notice when the value of the function is printed again then it didn’t display the first line as it was already displayed in the first line of output. Since all the text is displayed inline one and line two of the output so when the value of the function is printed again it returns an empty string.

You may also like, How to Create Countdown Timer using Python Tkinter.

Python Tkinter Display Text File

  • Python Open() has read mode set to default.
  • So every time we open a file we display it by default.
  • We have covered this topic in our above section. Please refer Python Tkinter Read Text File section for demonstration and explanation of this topic.

Python Tkinter Save to Text File

  • In this section, we will learn how to save the content of the text file Python Tkinter.
  • Every day while working on the computer we save files. So must be aware of the interface to do so.
  • We click on the save button, the saves with no message are already saved otherwise a file dialog, the user navigates to the location and then clicks on the save button. The file saves in that location.
  • Similarly, we will use the Python Tkinter filedialog module to generate a file dialog. Using file dialog user can save the file.

Code:

In this code, we have implemented writing file using python tkinter, save file using python tkinter and edit file using python tkinter. This is an entire application that be used as Notepad wherein user can write something, save and open the file.

from tkinter import *
from tkinter import filedialog

# functions 
def openFile():
    tf = filedialog.askopenfilename(
        initialdir="C:/Users/MainFrame/Desktop/", 
        title="Open Text file", 
        filetypes=(("Text Files", "*.txt"),)
        )
    pathh.insert(END, tf)
    tf = open(tf)
    file_cont = tf.read()
    txtarea.insert(END, file_cont)
   
    tf.close()

def saveFile():
    tf = filedialog.asksaveasfile(
        mode='w',

        title ="Save file",
        defaultextension=".txt"
        )
    tf.config(mode='w')

    pathh.insert(END, tf)
    data = str(txtarea.get(1.0, END))
    tf.write(data)
   
    tf.close()

ws = Tk()
ws.title("PythonGuides")
ws.geometry("400x500")
ws['bg']='#2a636e'

# adding frame
frame = Frame(ws)
frame.pack(pady=20)

# adding scrollbars 
ver_sb = Scrollbar(frame, orient=VERTICAL )
ver_sb.pack(side=RIGHT, fill=BOTH)

hor_sb = Scrollbar(frame, orient=HORIZONTAL)
hor_sb.pack(side=BOTTOM, fill=BOTH)

# adding writing space
txtarea = Text(frame, width=40, height=20)
txtarea.pack(side=LEFT)

# binding scrollbar with text area
txtarea.config(yscrollcommand=ver_sb.set)
ver_sb.config(command=txtarea.yview)

txtarea.config(xscrollcommand=hor_sb.set)
hor_sb.config(command=txtarea.xview)

# adding path showing box
pathh = Entry(ws)
pathh.pack(expand=True, fill=X, padx=10)

# adding buttons 
Button(
    ws, 
    text="Open File", 
    command=openFile
    ).pack(side=LEFT, expand=True, fill=X, padx=20)

Button(
    ws, 
    text="Save File", 
    command=saveFile
    ).pack(side=LEFT, expand=True, fill=X, padx=20)

Button(
    ws, 
    text="Exit", 
    command=lambda:ws.destroy()
    ).pack(side=LEFT, expand=True, fill=X, padx=20, pady=20)

ws.mainloop()

Output:

In this output, dummy text is written in text area. Now when user clicked on the save button a file explorer is prompted. User can navigate to to location where he want to save it after that click on save button. The file is saved on the system and can be opened by clicking on the open button.

python tkinter read textfile save file
Python Tkinter Save to Text File

Python Tkinter Write Text File

  • In this section, we will learn how to Write a Text File in Python Tkinter.
  • open(file_path, w) is used to write a file in an existing file.
  • open(file_path, w+) is used to write a file and if the file doesn’t already exist then it will create a new file.
  • While working with Python Tkinter we can pass either of them they both will work in the same way.
  • Please refer to our Python Tkinter Save to Text File section to see a demonstration.

Python Tkinter Edit Text File

  • In this section, we will learn how to Edit a Text File in Python Tkinter.
  • Edit means there some text already in the file and we want to change it.
  • In Python, File editing can be done using the append mode.
  • but in the case of Tkinter, You can simply open a file make changes, and save it again.
  • refer to our Python Tkinter Save to Text File section to see a demonstration.

Python Tkinter Create Text File

  • To create a Text file in Tkinter it is important to take some text area.
  • You can use canvas, entry, or Text widget to create a text area. We have used the Text widget in our case.
  • Once the Writing space is ready we need to create action buttons to save the file.
  • file dialog the module will be used to open file explorer for saving or opening the file.
  • Now in the end-user need to type some text on the provided writing space and when he will click on the save button a file explorer will pop up and he can save the file to the desired destination.
  • To see the implementation please refer to our Python Tkinter Save to Text File section.

Python Tkinter Close Text File

  • When ever any operation is started it is important to define when it will be closed.
  • Closing text file is important and considered to be a good practice.
  • Every time when we open a file it comes into an operation. System considers that we are working on it so some resources are assigned to it. Closing file tells a computer that task has been completed and now file is free now.
  • You my not observe any difference while executing program without closing file. But if you will work on bigger projects with other databases then you will notice the difference.
  • So it is good practice to close the file after use.

Syntax:

f = open("file_path", "mode")
    -------
    -------
f.close()

You may like the following Python tutorials:

In this tutorial, we have learned how to Read Text File in Python Tkinter. also we have covered these topics.

  • How to Open Text File in Python Tkinter
  • How to Read Text File in Python Tkinter
  • How to Display Text File in Python Tkinter
  • How to Save to Text File in Python Tkinter
  • How to write Text File in Python Tkinter
  • How to Edit Text File in Python Tkinter
  • How to Create Text File in Python Tkinter
  • How to Close Text File in Python Tkinter