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.
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.
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"
Open the file using the open() function, like this:
f = open(strPath)
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 = f.read()
Print out the contents of the file by printing the strText string, like this:
Run the program by pressing the "F5" key. The program will print the entire contents of the text file to the console.