Before session 6
1. Files
Watch the video:
2. Test
Go to Moodle and take the sixth test on the video lecture.
3. 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.
Example 1. Shoe size
The file foot.txt contains some data about foot lengths. The following program reads the data from the file, calculates a suitable shoe size for each foot length and prints the result out. The program prints Invalid input if the foot length cannot be converted into a number for some reason, and proceeds with the next line of the file.
def shoe_size(length): return 1.5 * (length + 1.5) ffile = open("foot.txt") for foot in ffile: try: f = float(foot) s = shoe_size(f) print("Foot length:", f, "Suitable shoe size is", int(round(s))) except: print("An invalid input") ffile.close()
Example 2. Upper case
The following program prompts the user for a file name, then the program reads the file and prints the content of the file (line by line) in the upper case. The program ends its work nicely whether the files exist 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()) fname.close()
4. Solve and submit
Exercise 1. Name in URL
Write a program that reads URLs of Tartu University users' webpages from a file called urls.txt and outputs the user names. The solution should have a function called find_name
that takes one parameter (URL) and returns the name (you can reuse the solution of the previous homework for finding a user name from an URL and make it as a function). You should create the file urls.txt yourself.
If the file urls.txt contains the following lines:
http://www.ut.ee/~koit/KT/index_eng.html http://www.ut.ee/~vilo/ http://www.ut.ee/~kiho/
then the output of the program should be
koit vilo kiho
Exercise 2. Numbered lines
Write a program which prompts the user for the file name and outputs all lines from the file with its line number. Make sure that the program ends its work nicely whether the file exist in the folder or not (use try-except).
If the content of the file names.txt is as follows:
Jon Snow Arya Stark Tyrion Lannister Eddard Stark Melisandre
then the program output is the following:
Enter the file name: names.txt 1. Jon Snow 2. Arya Stark 3. Tyrion Lannister 4. Eddard Stark 5. Melisandre
Go to Moodle and upload your solutions into Exercises 6.