Txt Files Reading - Lakelands Computing

Title
Go to content
Reading Text Files
When you are working with large amounts of data, you are going to want to store it outside of the actual code of the program. There are a number of ways you can do this with Python including CSV, TXT, XLS/XLSX (Excel), sas7bdat (SAS), Stata, Rdata (R). We are going to look at using txt files.

Once you have the text file the first step is to open it. This doesn't read the contents, just opens the file. You have to open the file to do anything with it, and you should close it when you are done working with the file.

To Open a txt file (for the purpose of the examples, I have a text file called Cars.txt) :

  • file = open("cars.txt","r")

This would open the file in read mode, that is what the "r" is for. You can also in write - "w" and append "a" modes.  Note how the file name and extension (the .txt) is inside " ". The open files is stored in the variable called file. We can refer to that variable rather than the file name now.

With the file open you now have options on how to read it.

This would read (and print)  the entire file.

  • print (file.read())

Sometimes you want that, sometimes you may want to only read the first few characters

  • print(file.read(10))

This prints the first 10 characters. (This can be useful if the first few characters are the latest data in the file etc.)

You can also read a line from the file

  • print (file.readline())
  • print (file.readline())

Would print the first two lines.

You can use the readline method with a for loop to read the file line by line:

  • for line in file:
    • print (line )

To read the entire file line by line using readlines() :

  • print(file.readlines())

And we can use readlines () to let us access a specific line from the file:

  • allLines = file.readlines()
  • print (allLines[4])

This reads all the lines into a variable called allLines and then prints out the 5th line (remember we count from 0)

Closing the file

  • file.close()

Always close your files. It may cause problems if you don't with files being unavailable to read or write at a later point. Note you can avoid the need to keep closing files by using the with method. (Most experienced programmers use this)

  • with open ("cars.txt","r") as file:

All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content