Read & Search Files

Reading from a file


Make sure that you have opened your file in Read Mode by using ‘rt’ in the open file line.

You need to save the contents of the file into a variable that you can then print. Below is an example where ‘Contents’ is an example variable:

files8

This would print all of the data in your file. If you instead wanted to look at the file line-by-line then you could use a loop:

files9

In the example above the end=” “ part is used to make sure that there is not a blank space between each line.

If you want to hide certain data values from being printed then you could use a not in command:

files10


Reading specific lines from a file


Sometimes it is necessary to only print certain lines, perhaps based on an input or calculation – such as a response printed from a file if a counter exceeds a certain value.

I have created a file with a number of statements, one on each line. I want to create a simple ‘magic 8 ball’ program where the user enters a number between 1 and 6 and a line is read from the file depending on that number.

py1

I want to open the file first in read mode and then create a variable which holds all of the different lines in the file, which I have simply named lines.

py2

Next I have asked my question using an input line and then used if and elif statements to check the user’s response and then print a certain line based on that response. Remember that Python starts at 0, not 1, so I wrote (lines[0]) to read in the first line.

py3

The program above is an unfinished example, I did not have a print statement for each line in the file and I did not add any validation. Below is an example of the file working:

py4


Searching through Files


 


< Back to Section Ten