Institute of Computer Science
  1. Courses
  2. 2025/26 fall
  3. Introduction to Programming (MTAT.03.236)
ET
Log in

Introduction to Programming 2025/26 fall

  • Home
  • Grading
  • Links

Before session 6

Files

Work through topics from the reading materials or watch the videos.

Test

Go to Moodle and take the sixth test on the video lecture.

Homework

The deadline for homework is Monday. Still, it would be good to start with homework already before the session.

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 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", round(s))
    except:
        print("Invalid input")

ffile.close()

Example 2. Upper case

The following program asks for the file name, then the program reads the file and prints the contents of the file (line by line) in the upper case. The program works nicely with all the files which exist and do not exist.

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()

Homework

  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment