Opening and reading text files in Python

So far a lot of projects that I have worked on in Python have utilized external files for some kind of processing. Early on I had to become familiar with the open() function and some supporting functions for working with external files. Initially I worked with plain text files, but have moved on to more complex file types and have learned how to use a few new libraries to help process those. For this post I will stick with plain text.

The open() function does just what it describes and opens the specified file. This function takes two parameters: filename and mode.

open('file.txt','r')

The filename parameter is a text string for the file one wants to open and will need to include the full path if necessary. The mode parameter has the following options:

  • Read "r" - The read parameter opens the file for reading. This is the default value if this parameter is left blank. If the file does not exist an error message will be returned.

  • Append "a" - The append parameter opens the file for appending additional data. If the file does not exist the function will create a new file.

  • Write "w" - The write parameter opens the file for writing data. This parameter will overwrite and existing file or create a new file.

  • Create "x" - The create parameter creates the specified file. An error will be returned if it already exists. Additionally, one can specify if the file should be handled as binary "b" or text "t" (text is the default mode).

Once the text file has been opened it is time to read the contents for processing. I have used both the read() and readlines() functions in the projects I have worked on. The read() function will read the entire document as one block of text. The readlines() function will read each line of text as a list. Once the text is in a readable format for Python one can start manipulating or processing it.

file = open('file.txt','r')

readTheFile = file.read()
print(readTheFile)
This is some text.
Here is some additional text.

readlinesTheFile = file.readlines()
print(realinesTheFile)
['This is some text.\n','Here is some additional text.']

Of course, once you are finished with the file it is good practice to close it and that is where the close() function comes into play.

file.close()

You can get a bit fancier and have Python close the file automatically once one has finished processing it, but I will save that for another post.

So there you have it, the basics of opening, reading and closing files in Python. I am sure there are many ways people have discovered with file management in Python so if you have a tip please leave it in the comments!