0% found this document useful (0 votes)
34 views

Lesson 7 File Handling

The document describes a program to load town data from a CSV file into Python, search the data, and display results. It provides tasks to open and read the CSV file, split the data into a list of lists, search for a town or county name, and define functions to modularize the code. The tasks would have the program take user input to search for a town or county, loop through the list to find matches, and print the matching town or county details. Functions are suggested to handle reading the file, splitting the data, and searching.

Uploaded by

e
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Lesson 7 File Handling

The document describes a program to load town data from a CSV file into Python, search the data, and display results. It provides tasks to open and read the CSV file, split the data into a list of lists, search for a town or county name, and define functions to modularize the code. The tasks would have the program take user input to search for a town or county, loop through the list to find matches, and print the matching town or county details. Functions are suggested to handle reading the file, splitting the data, and searching.

Uploaded by

e
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Name: Form: Date:

Lesson 6
File Handling

A file is some information or data which stays in the computer storage devices. You
already know about different kinds of file, like your music files, video files, text files.
Python gives you easy ways to manipulate these files. Generally we divide files in two
categories, text file and binary file. Text files are simple text whereas the binary files
contain binary data which is only readable by computer.

Example:
Open a new Python file and write in the following code:

Save this to a new folder called file handling, run the program and then open the folder to see what
you have created.

Explain what the code created, did you spot any problems?

Now run the code again, what happened?

Now use comments (#) to show that you understand what it does, paste your commented code below:

OCR GCSE (9-1)


Name: Form: Date:

Adapt your file so it is the like the one above, save as newline.py

Run the file and check the output – what is different this time, why?

Adapt your file again so it is the same as the one below:

Run the file and check the output – what is different this time, why?

Can you spot the deliberate error? Run the file two or three more times, what is wrong with the
output?

OCR GCSE (9-1)


Name: Form: Date:

Town Program

Aims:

1. To load a towns list (see table below) into your Python program.
2. To search for a town with a particular name and display all the details for that town.
3. To search for counties containing certain parts (e.g. Yorks or Sussex).

Town County Population Area


Berwick Upon Northumberland 12870 468
Tweed
Bideford Devon 16262 430
Bognor Regis West Sussex 62141 1635
Bridlington East Yorkshire 33589 791
Bridport Dorset 12977 425
Cleethorpes Lincolnshire 31853 558
Colwyn Bay Conway 30269 953
Dover Kent 34087 861
Falmouth Cornwall 21635 543
Great Yarmouth Norfolk 58032 1467
Hastings East Sussex 85828 1998
Maidstone Kent 89684 2173
Morcambe Lancashire 49569 1302
Scarborough North Yorkshire 38364 772
Skegness Lincolnshire 16806 512
Torquay Devon 62968 1568
Whitby N Yorkshire 13594 321

The following Python concepts will be practised in the ‘Towns List’ program:

1. Reading in from a file using open(“Townsfile.csv”, “r”)


2. .split()
3. for loop
4. Making an empty list newlist = []
5. Appending to a list newlist.append(eachItem)
6. Multi-dimensional lists
7. Ask a user to input() a town or county
8. Check if the town is in newlist
9. Recap functions, e.g. def searchTown():
10. Menu structure def displayMenu():
11. Writing the main program to call all the functions so they run
12. while True: to loop main program

For each of the tasks, provide print screens of the code and output.

Task 1

Open a connection to the townsfile.csv file in using the read (“r”) mode using:

OCR GCSE (9-1)


Name: Form: Date:

temp = open("townsfile.csv", "r") #opens connection to csv file


towns = temp.read() #reads into a string called towns
temp.close() #closes connection to file
print(towns) #to see what has happened!

NB: you need to copy the townsfile.csv file into the same folder as your python program or it
will not work!

This has read the file into your program as a huge long string called towns but it has also read in the
invisible end of line markers (\n). This is a problem and we now need to split it into individual towns
so we can store them in Python.

Task 2

We need to split the towns string up and make it into a list. First split up using the end of line marker
“\n” which will split the string into individual lines and make a list called eachTown:

eachTown = towns.split("\n")

NB: Try print(eachTown) to see what has happened

Task 3

We need to then split this list again this time using commas so that we can store every town in a
separate record. To do this we will split eachTown again using the comma separator “,”:

record = eachTown.split(",")

We need to repeat the splitting by comma for every item (town) in the eachTown list. So we use a
for loop:

for eachItem in eachTown: #loops through each record/line in the


list

record = eachItem.split(",")

print(record)

There is a problem as it only stores the last record (town), but we need all of them.

Tasks 4 & 5

We need to create an empty list called newlist to store each of these new records in:

newlist=[]

OCR GCSE (9-1)


Name: Form: Date:

We can then .append() each record into the newlist in the following way:

newlist.append(record)

As we need to repeat this for each record it would be a good idea to put this statement indented into
the for loop, e.g.

newlist=[]

for eachItem in eachTown:

record = eachItem.split(",")

newlist.append(record)

NB: don’t put the command to create an empty string in the for loop as it will keep emptying
it!

Task 6

If you now ‘print’ the newlist to the screen using print(newlist)you will see what you have
created:

We have made a multi-dimensional or 2D array (or list as they are called in Python). The first item in
the list is . This is in
index 0 so try:

print(newlist[0])

What is in newlist[3]?

……………………………………………………………………………………………………………

……………………………………………………………………………………………………………

To access different items in a multi-dimensional array you can use the following example.

To find ‘Dover’ you would use newlist[7][0]. Try printing it to see if it works!

OCR GCSE (9-1)


Name: Form: Date:

Predict what is in newlist[0][3]?


………………………………………………………………………………………………….…..

Predict what is in newlist[3][2]?


………………………………………………………………………………………………….…..

Predict what is in newlist[10][0]?


………………………………………………………………………………………………….…

NB: Don’t forget to start at index of 0 for the first item in the list! Check your answers in
Python.

Task 7

We now need to add some code that will search the newlist to find a town that the user inputs (aim 2).
Ask your end user to input the name of the town they are searching for and save their input into a
variable called whatTown:

whatTown = input("Which town are you looking for?\n")

Task 8

We need to search repeatedly through the newlist to see if whatTown is in the list and then print the
details of that town:

for eachItem in newlist:

if whatTown in eachItem:

print(eachItem)

Can you think of a better way to display the results?

Try changing print(eachItem)inside the loop to:

print("Town:", eachItem[0])

Can you finish it for the other fields (County, Population and Area)?

Can you do a similar bit of code that searches by County?

Task 9

There are different parts of the program that perform different tasks, such as:
 Reading from file
 Splitting the file
 Searching for a town
 Searching for a county
These could be written as separate functions or procedures which are sub-programs or sub-routines:

def readsFile():
temp = open("Townsfile.csv", "r")

OCR GCSE (9-1)


Name: Form: Date:

towns = temp.read()
temp.close()
return towns

NB: that at the end of this function we return towns. This is so that whatever is stored in the
towns list is ‘returned’ out of the function and is made available for the rest of the program. If we did
not do this we would not be able to use towns elsewhere in the program.

Can you now make a function/procedure for each of the tasks? Define them using:
def readsFile():
def splitFile(towns):
def searchTown(thelist):
def searchCounty(thelist):

NB: that the splitFile(), searchTown() and searchCounty() functions all have a parameter in the
brackets after the name of the function. This is because you need to pass something into the function.
In the latter two cases you need thelist to go into the function, so you can search in it!

NB: for the searchTown() and searchCounty() functions you do not need to return a value from the
function, you can simply use print to display the town/county details to the screen.

Task 10

The program could be improved by adding a menu for the end user to choose what they want to
perform.
def displayMenu():
print("-------------------------")
print("Welcome to the Towns List")
print("-------------------------")
print()
print("Would you like to search for: \n")
print("a - a town by name")
print("b - a county")
print("q - to quit")
print("Please enter your choice a, b or q: \n")
choice = input()
return choice

Task 11:

At the bottom of your program you can now write the main program. This will call each of the
functions, so that they run.
allTowns = readsFile()
# calls the readsFile() function which returns a string called towns. You need to store this into a
variable (preferably with a different name, e.g. allTowns).
townsList = splitFile(allTowns)
# you then call the splitFile() function using the allTowns that the previous function call created!

OCR GCSE (9-1)


Name: Form: Date:

userChoice = displayMenu()
#this calls the displayMenu function which prints the menu, asks the user for their choice and then
returns it and saves it here as userChoice.

# the next block of code uses another if statement to work out what function to run, depending on
which choice the end user makes. For example, if they choose ‘a’ then call the searchTown() function,
else if they choose ‘b’ call the searchCounty() function, else if they choose ‘q’ print ‘Goodbye’.

if userChoice == "a":
searchTown(townsList) #calls function using the townsList created 3 lines above
elif userChoice == "b":
searchCounty(townsList)
elif userChoice == "q":
print("Goodbye!")

You can add a bit of validation to this program by adding a final else: to the if, elif, statement which
means that if anything other than ‘a, b or q’ is input then an error message will come up on the screen.
E.g.

else:
print("Invalid input please enter a, b or q”)

Task 12:

To make the program loop you can add a conditional loop using a while. If you say while
True: it will continue for ever as True is always True! This makes an ‘infinite loop’.

#main program
while True:
allTowns = readsFile()
townsList = splitFile(allTowns)
userChoice = displayMenu()
if userChoice == "a":
searchTown(townsList)
elif userChoice == "b":
searchCounty(townsList)
elif userChoice == "q":
print("Goodbye!")
break
else:
print(“Invalid input please enter a, b or q”)

OCR GCSE (9-1)


Name: Form: Date:

NB: The break command allows you to ‘break’ out of this infinite loop any time you want to. We
can use it when the user wants to quit, so we have added it after the program prints ‘Goodbye!’.

OCR GCSE (9-1)

You might also like