How to a Read Text File in Python

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.

File input and output is a very important function in programming languages. The Python programming language is capable of reading text from a text file on your computer. This is very useful for storing configuration settings and data for your program. Instead of entering configuration data every time you execute your Python script, you could have it read a configuration file and fill in the settings from that. Learning file input is an important step as a programmer. You can learn how to read a text file using Python in just a few minutes.


Step 1

Open the IDLE text editor that comes with the Python programming language. The IDLE program is located in your Program Files (or Applications for Macintosh) within the Python directory. A blank source code file opens in the IDLE text editor window.

Video of the Day

Step 2

Declare a string variable that holds the path to the text file you want to read in Python. For example, if you have a text file named "etc.txt" on your C: drive, you can write the following to declare the string:


strPath = "C:\etc.txt"

Step 3

Open the file using the open() function, like this:

f = open(strPath)


Step 4

Read the contents of the file using the read() function. The output of the read() command can be stored in a string for printing out later, like this:


strText =

Step 5

Print out the contents of the file by printing the strText string, like this:



Step 6

Run the program by pressing the "F5" key. The program will print the entire contents of the text file to the console.

Video of the Day



references & resources

Report an Issue

screenshot of the current page

Screenshot loading...