Homework for Week 8
After this week you can
- Open and close files
- Read files line by line
- Process lines read from the file
- Write files
Files
The basics of manipulating files include opening a file, reading data from or writing data to it, and closing the file. Often the files are text files and are made up of lines that are more or less human-readable. Such files are processed line by line, applying the needed operations on each line after it is read.
Watch the video lectures:
Slides in English
Textbook in English
Quiz
Go to Moodle and solve the quiz on files.
Examples
NB! Make sure that the text files (.txt) are in the same folder as your Python code. Otherwise, Python will not find the files.
Shoe size
The file footlengths.txt contains data about foot lengths. The following program reads the data from the file, calculates the suitable shoe size for each foot length, and prints the result. If the foot length cannot be converted into a number for some reason, then the program prints "Invalid input" and proceeds to the next line in the file.
def shoe_size(length): return round(1.5 * length + 2) ffile = open("footlengths.txt") for foot in ffile: try: f = float(foot) s = shoe_size(f) print("Foot length:", f, "Suitable shoe size is", s) except: print("Invalid input") ffile.close()
The try and except statements here are needed for converting the line into a number. If the conversion produces an error, then the message "Invalid input" is printed, and the loop continues with the next line of the file.
Uppercase
The following program prompts the user for a filename, reads the file, and prints the content of the file (line by line) in uppercase. The program finishes its work nicely regardless of whether the file exists in the folder or not.
fname = input("Please enter the file name: ") try: ffile = open(fname) except: print("File cannot be opened:", fname) else: for line in ffile: print(line.strip().upper()) ffile.close()
Here the try and except statements are used to catch the situation where the file with the requested name doesn't exist. In that case, the program prints a message and terminates. If the file exists, then the execution goes to the else part.
Exercises
1. Numbered lines
Write a program that prompts the user for filename and outputs all lines from the file, numbering them with consecutive integers. The program should finish nicely regardless of whether the file exists in the folder or not (use try-except).
For example, if we have the file names.txt with the following content:
Jon Snow Arya Stark Tyrion Lannister Eddard Stark Melisandre
then the program should output:
Enter filename: names.txt
1. Jon Snow
2. Arya Stark
3. Tyrion Lannister
4. Eddard Stark
5. Melisandre
Second example:
Enter filename: games.txt
File doesn't exist
2. Machine translation
Write a program that prompts for two filenames. The first name belongs to an existing text file, the second name is the name of a new file that may not yet exist.
The task of the program is to take the content of the first file, replace every word "Hello" with "Hi", and write the result in the second file. On the screen, it should print how many replacements were made.
Example
Content of the file source.txt:
Hello! Hello Kitty Hello-Hello
Input and output:
Enter source file name: source.txt
Enter destination file name: destination.txt
4 replacements were made.
Content of the resulting file destination.txt:
Hi! Hi Kitty Hi-Hi
Hint
>>> 'abcabca'.count('ab')
2
3. Sale
A shop sells different kinds of products. The shop owner has written the prices of all products in the file prices.txt. For example, bananas cost 1 euro per kilogram, tomatoes cost 3 euros, etc. The file has two lines for each product: product name on one line and its price on the following line. For example, the content of the file may be:
bananas 1 tomatoes 3 avocados three walnuts 18-19 yellow plums 4.5
For a sale, the shop owner wants to lower all prices by 10%. Write a program that reads the products and prices from the file, computes the new prices, if possible, and prints them on the screen, rounded to two decimal places.
The output should contain one line for each product. If price conversion is successful, then the line contains the name of the product and its new price. If price conversion is not successful, then the program should inform the user that the price for that product couldn't be computed.
New price for bananas is 0.9 euros.
New price for tomatoes is 2.7 euros.
Cannot convert the price for avocados.
Cannot convert the price for walnuts.
New price for yellow plums is 4.05 euros.
Autotester. The program doesn't prompt the user for anything, the data will always be read from the text file prices.txt. In the output, the data for each product must be on a separate line.
Submit your solutions
Submit your solutions of exercises 1, 2, and 3 in Moodle under the names home1.py, home2.py, and home3.py.