Lesson 7 File Handling
Lesson 7 File Handling
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 use comments (#) to show that you understand what it does, paste your commented code below:
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?
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?
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).
The following Python concepts will be practised in the ‘Towns List’ 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:
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")
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:
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=[]
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=[]
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!
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:
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:
if whatTown in eachItem:
print(eachItem)
print("Town:", eachItem[0])
Can you finish it for the other fields (County, Population and Area)?
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")
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!
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”)
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!’.