Python 10b - Read & Search Files

Reading from a File

To read and print from a file you must open it in read mode by typing "r" instead of "a".

If you are writing and reading in the same program make sure you close the file in append mode before you open it in read mode.

The program below uses the Customers.txt file from the last section.

A simple for loop can be used to print each line of the file.

The end = "" code just prevents an empty space between each line.

Practice Task 1

Open one of the files that you used in Section 10a and print each line.

Example solution:

Reading Specific Lines from a File

Sometimes it is necessary to only print certain lines.

The following example uses a file where I have written a sentence of advice on each line.

The user is asked to enter a number between 1 and 6. 

If they enter 1 the first line of the file is printed. If they enter 2 the second line of the file is printed etc.

Remember Python starts counting everything at 0 so each line is actually a digit less than you would expect.

Square brackets must be used to denote the line to print: [1] not (1).

The end = "" code is not necessary but removes empty space after the line.

Practice Task 2

Create a text file (saved in the same folder as your Python file) with a list of video games.

Ask the user to enter a number between 1 and 10.

Print the line for the number that they input.

Example solution:

Searching Through Files

A for loop is used to search through a file, line by line.

First, an input line is used to allow the user enter their search term.

If the term that is being searched for is found then the whole line is printed.

The example below uses a variable named found to state if there is a match when the file is searched.

If the search term is found then the found variable is changed to true.

If the search term is not found, the found variable remains as false so the 'no customers found' statement is printed.

Practice Task 3

You should have completed Practice Task 2 from Section 10a (the A Level task).

Add extra code to that program so that you can search for specific students.

Example solution:

© CSNewbs 2019