Python - How To Read Text File

Submitted by: 
Visitors have accessed this post 335 times.

In this tutorial we will create a How To Read Text File Using Python. Python has a design philosophy which emphasizes code readability. Python is very easy to learn the syntax emphasizes readability and it can reduces time consuming in developing. You can use this to convert the units value. So let's now do the coding...

Getting started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python

Importing Modules

After setting up the installation and the database, run the IDLE and click file and then new file. After that a new window will appear containing a black file this will be the text editor for the python.

Then copy code that I provided below and paste it inside the IDLE text editor.

  1. from tkinter import *

Setting up the Main Frame

After importing the modules, we will now then create the main frame for the application. To do that just copy the code below and paste it inside the IDLE text editor.

  1. #==================================MAIN FRAME=====================================
  2. root = Tk()
  3. root.title("Python - Check File Exists")
  4. width=450
  5. height=350
  6. screen_width=root.winfo_screenwidth()
  7. screen_height=root.winfo_screenheight()
  8. x=(screen_width/2) - (width/2)
  9. y=(screen_height/2) - (height/2)
  10. root.geometry("%dx%d+%d+%d" % (width, height, x, y))
  11. root.resizable(0, 0)

Assigning Variables

This is where the we will assign the variables. This code will assign each of the variables to be use later in the application.

  1. #=================================VARIABLES=======================================
  2. FILE = StringVar()

Designing the Layout

After creating the Main Frame we will now add some layout to the application. Just kindly copy the code below and paste it inside the IDLE text editor.

  1. #=================================FRAMES==========================================
  2. Top = Frame(root, relief=SOLID, bd=1)
  3. Top.pack(fill=X)
  4. Mid = Frame(root)
  5. Mid.pack(pady=20)
  6. Left = Frame(Mid)
  7. Left.pack(side=LEFT)
  8. Right = Frame(Mid)
  9. Right.pack(side=RIGHT)
  10. BelowMid = Frame(root)
  11. BelowMid.pack()
  12. Bottom = Frame(root)
  13. Bottom.pack()
  14. BottomPane = Frame(root)
  15. BottomPane.pack()
  16. #=================================LABEL WIDGETS===================================
  17. lbl_title = Label(Top, text="Read File Text", font=('calibri', 16))
  18. lbl_title.pack()
  19. lbl_txt = Label(Left, text="Enter a text file", font=('calibri', 15))
  20. lbl_txt.pack()
  21. lbl_txt2 = Label(Bottom, text="Result", font=('calibri', 15))
  22. lbl_txt2.pack()
  23. lbl_status = Label(Bottom,font=('calibri', 12))
  24. lbl_status.pack()
  27. #=================================ENTRY WIDGETS===================================
  28. txt_file = Entry(Right, font=('calibri', 15), textvariable=FILE)
  29. txt_file.pack()
  31. #=================================BUTTON WIDGETS==================================
  32. btn_check = Button(BelowMid, text="Read File", command=Read_File)
  33. btn_check.pack(pady=10)

Creating the Main Function

This is where the code that contains the main functions. This code will read a text file when clicked. To do that just copy and write these blocks of code.

  1. #=================================METHODS=========================================
  2. def Read_File():
  3. if FILE.get() == "":
  4. lbl_status.config(fg="Orange", text="Please enter something")
  5. for widget in BottomPane.winfo_children():
  6. widget.destroy()
  7. else:
  8. for widget in BottomPane.winfo_children():
  9. widget.destroy()
  10. file = open(FILE.get() + ".txt", "r")
  11. chars = [line.rstrip('\n') for line in file]
  12. for i in range(len(chars)):
  13. exec ('Label%d=Label(BottomPane,text="%s")\nLabel%d.pack(anchor=W)' % (i, chars[i], i))
  14. file.close()

Initializing the Application

After finishing the function save the application as This function will run the code and check if the main is initialize properly. To do that copy the code below and paste it inside the IDLE text editor.

  1. #=================================INITIALIZATION==================================
  2. if __name__ == '__main__':
  3. root.mainloop()

There you have it we just created a How To Read Text File Using Python. I hope that this simple tutorial help you for what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.