How to a Read Text File in Python

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.

Things You'll Need

  • Computer with Python 3.2 programming language installed (see Resource)

Instructions

    • 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.

    • 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"

    • 3

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

      f = open(strPath)

    • 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 = f.read()

    • 5

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

      print(strText)

    • 6

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

Related Searches

References

Resources

You May Also Like

Related Ads

View Blog Post

Enter the Geek Vs Geek Giveaway and Win a Roku!