06. Input/Output
06. Input/Output
Some of the following exercises require text files. These can be downloaded using the GitPub link below:
Starter code
Files and Error Handling β Exercises
Exercise 1 β Read a file
Create a program that opens a file called message.txt and prints every line in the file.
The file contains:
Hello!
Welcome to Python.
This is our first file.Use readlines() to read the contents.
Remember to close the file when you are finished.
Bonus: Rewrite the program using with open(...).
Exercise 2 β Count the lines
Create a function that receives a filename and returns the number of lines in that file. (You have to create the file yourself, it's not in the start-folder.)
For example, given:
Alice
Bob
Charlie
Diana
Evethe function should return 5.
The main program should ask the user for a filename, call the function and print the result. The main program keeps on asking filenames until the users enters 'STOP' as filename. Then the program exits.
And a reminder: the main program prints the result, not the function.
Exercise 3 β Create a new file
Create a program that asks the user for their name and age.
Write the information to a new file called person.txt.
The file should contain something similar to:
Name: Alice
Age: 23Use the w mode.
Put the code that creates and writes the file in a function.
The main program should call the function.
Think about: What happens if person.txt already exists?
Exercise 4 β Add information
Create a program that keeps a simple log in a file called log.txt.
Ask the user for a message and add it to the end of the file.
Every message should be written on a separate line.
For example, after running the program several times, the file could contain:
Program started
User logged in
File downloaded
Program stoppedUse append mode.
Create a function that adds one message to the log.
The main program should ask for the message and call the function.
Exercise 5 β Copy selected lines
Create a function that receives two filenames. The first file is in the start-folder as "start.txt".
The first file contains a list of names:
Alice
Bob
Charlie
Diana
Eve
Frank
GraceThe function should read the file and create a second file containing only the names that start with the letter A, C or E.
For the example above, the new file should contain:
Alice
Charlie
EveUse readlines() to read the original file and writelines() to write the selected lines.
Exercise 6 β CSV reader
Use the file called people.csv:
name,age,city
Alice,23,Geel
Bob,31,Antwerp
...Write a program that uses csv.reader to read the file.
Display each person like this:
Alice lives in Geel and is 23 years old.
Bob lives in Antwerp and is 31 years old.
...Put the reading and processing of the CSV file in a function.
The function should return the generated lines instead of printing them.
The main program should print the returned result. Beware of the accents!
Exercise 7 β CSV statistics
Use the file hardware.csv:
product,price,quantity
Keyboard,49.99,3
Mouse,24.50,5
Monitor,189.99,2
USB cable,8.99,10
Webcam,59.99,4Write a function that reads the CSV file using csv.reader.
Calculate the total value of all products.
For example, the total value of a product is:
price Γ quantityThe function should return the total value.
The main program should print it with two decimal places.
Extra: Create a second function that returns the name of the product with the highest total value.
Exercise 8 β CSV DictReader
Use the file employees.csv:
name;department;salary
Alice;IT;3200
Bob;Sales;2800
Charlie;IT;3500
...Write a program that uses csv.DictReader.
Create a function that receives a department name and returns all employees working in that department.
For example, asking for IT should return information about:
Alice
Charlie
Frank
...The main program should ask the user for a department and display the matching employees.
Extra: Instead of returning the complete rows, return only the names.
Exercise 9 β Update a text file
Create a file called tasks.txt:
Buy milk
Finish Python exercises
Call Alice
Clean the kitchen
Go cyclingWrite a program that asks the user for a task.
The program should look for that task in the file and, if it exists, replace it with:
DONE: <task>For example, if the user enters:
Call Alicethe file should become:
Buy milk
Finish Python exercises
DONE: Call Alice
Clean the kitchen
Go cyclingYou will need to:
- Read the existing contents.
- Change the appropriate line.
- Write the contents back to the file.
Put the file processing in a function.
Think about: Why can't you simply replace the text while reading the file line by line with normal r mode?
Error Handling
Exercise 1 β A number
Ask the user to enter a number.
Convert the input to an integer and print the number.
If the user enters something that isn't an integer, display:
That is not a valid number.Use try and except.
Create a function that converts the input and returns the number.
The main program should deal with displaying the result or error message.
Test the program with:
42
-17
hello
12.5Exercise 2 β Divide two numbers
Create a function that receives two numbers and returns the result of dividing the first by the second.
Ask the user for both numbers.
Handle both of these possible errors:
- The user enters something that isn't a number.
- The user tries to divide by zero.
For example:
First number: 10
Second number: 0
Cannot divide by zero.Try to use different except blocks for the different errors.
Exercise 3 β List position
Start with this list:
languages = ["Python", "Java", "C#", "JavaScript", "Go"]Ask the user for a position and display the corresponding language.
For example:
Position: 2
C#Handle:
- A position that isn't a valid integer.
- A position that doesn't exist in the list.
Test both positive and negative indexes.
For example:
Position: -1
Goand:
Position: 10
There is no language at that position.Exercise 4 β A dictionary lookup
Use this dictionary:
prices = {
"apple": 1.20,
"banana": 0.80,
"orange": 1.50,
"pear": 1.30
}Ask the user for the name of a fruit and display its price.
Handle the situation where the requested fruit isn't in the dictionary.
For example:
Fruit: apple
Price: 1.20and:
Fruit: pineapple
Unknown fruit.Extra: Make the function perform the lookup and return the price. Let the main program handle the error message.
Exercise 5 β What kind of error?
The following function contains several possible errors:
def calculate(numbers, position, divisor):
value = numbers[position]
return value / divisorUse this list:
numbers = [10, 20, 30, 40, 50]Ask the user for:
- an index
- a divisor
Call the function.
Your program should correctly handle:
- invalid integer input (
ValueError) - an index outside the list (
IndexError) - division by zero (
ZeroDivisionError)
Give the user a useful message for each situation.
For example:
Index: 10
There is no value at that index.Do not simply display the technical Python error message.
Exercise 6 β Does the file exist?
Ask the user for the name of a text file.
Try to open and read the file.
If the file doesn't exist, display:
The file could not be found.If it does exist, display its contents.
Use try and except FileNotFoundError.
Put the file-reading code in a function.
Extra: Use else so that the code that processes the successfully opened file is kept separate from the error handling.
Exercise 7 β else and finally
Create a program that manually opens a file:
notes.txtUse the following structure:
try
open the file
read the file
except
handle an error
else
process the contents
finally
close the fileThe program should:
- Try to open
notes.txt. - Read its contents.
- Display the number of lines in the file.
- Handle
FileNotFoundError. - Close the file in
finally.
Think carefully about why finally is useful here.
The file should be closed whether reading succeeds or an error occurs.
Extra: Add another possible error and handle it separately.
Exercise 8 β Creating a file
Ask the user for a filename.
The program should create a new file with that name and write a short message into it.
Use file mode x, so that an existing file is not overwritten.
Handle:
FileExistsErrorwhen the file already exists.PermissionErrorwhen Python isn't allowed to create the file.
For example:
Filename: notes.txt
The file already exists.Put the file creation in a function.
Extra: Use else to print a success message only when the file was created successfully.
Exercise 9 β A robust CSV reader
Create a program that reads a hardware.csv:
name,price,quantity
Keyboard,49.99,3
Mouse,24.50,5
Monitor,189.99,2
USB cable,8.99,10
Webcam,59.99,4The program should ask the user for a filename and a product number.
It should then display the total value of that product:
Product: Monitor
Total: 379.98Handle as many relevant errors as you can.
At minimum, consider:
- The file doesn't exist.
- The CSV row doesn't contain the expected information.
- The product number isn't a valid integer.
- The product number is outside the available rows.
- A price or quantity contains invalid numeric data.
Try not to put the entire program inside one giant try block.
Think about which operation can cause which exception and put the try/except blocks around the appropriate code.
Extra: Use csv.DictReader instead of csv.reader.
Exercise 10 β A small file-processing program
Create a program that processes a file containing ages and cities (people.csv):
name,age,city
Alice,23,Geel
Bob,31,Antwerp
Charlie,19,HasseltAlthough you have the filename, ask the user to enter it in the program.
The program should:
- Open the file.
- Read the people using
csv.DictReader. - Calculate the average age.
- Display the result.
- Close the file.
Make the program robust against errors.
At minimum, handle:
FileNotFoundErrorPermissionErrorValueErrorKeyErrorTypeError
Some of these errors may require you to deliberately create a faulty input file to test them.
Use:
tryfor operations that can fail.exceptfor handling known errors.elsefor code that should only run when everything in thetryblock succeeded.finallyto make sure the file is closed.
Challenge
Create a second, deliberately faulty CSV file:
name,age,city
Alice,23,Geel
Bob,hello,Antwerp
Charlie,twelve,Hasselt
...Run your program with both files.
Your program should not crash when it encounters the faulty file.
Instead, it should give the user a useful explanation of what went wrong.
Extra challenge: Modify the program so that one invalid student does not prevent the other valid students from being processed.