Part 6
Intro to Programming
9.10.2025
Last Week
Feedback from Part 5
Reading files
Typical action in programs
Using text files is easy in Python
Other file formats may be more complicated
Example
Reading file contents
with-block handles automatic closing of file
Handling files one row at a time
Method read reads the contents of the entire file
Often, it's easier to read file one row at a time
This is easy with the for statement
CSV Files
Comma Separated Values
Several data points in one row, separated with suitable character (i.e. a separator)
Splitting strings
String can be splitted into a list with the split method
The separator character is provided as an argument
Reading same file several times
File can be read in with-block only once
Removing extra characters
Reading data from file also returns line feed characters
Easiest way to get rid of these is to use the strip method
Creating a file
New file can be created by providing character 'w' as the second argument for the open function
Note, that if file exists, is will be overwritten!
Writing to file
Lines can be written to the file with the write method
Please note, that the linefeeds must be added manually
Appending data to file
New data can be appended after the existing data in the 'a' file mode
Writing a CSV file
Emptying and removing files
Validating inputs
Typical examples of erroneous input data:
Validating input (2)
It's often possible to prepare for erroneous data
Inputted data can be validate with conditions
Exceptions
Some errors are difficult to check with conditional statements only
Exceptions are errors that occur during the execution of programs
Preparing for exceptions
Exceptions can be caught with try-except structure
Typical exceptions
ValueError
TypeError
IndexError
ZeroDivisionError
Exceptions in file handling
More than one except block
If more than one error may be thrown in the try block, it can be followed with more than one except block
Undefined exception
All possible exceptions can be caught by not defining the exception in the except block
Note, that this also catches the errors made by the programmer
Passing exceptions
Exception thrown in a function is passed back to the caller of the function
Throwing exceptions
Exception can be thrown manually with keyword raise
This is a good method for handling e.g. invalid parameters in functions
Local variables
Variables defined in functions are only visible inside functions
Keyword global
Variables defined in the main program can be used inside functions with keyword global
This is, in general, a bad idea. Instead of side effects, the functions should return a value
Next week
Modules
Random
Handling times and dates
More file handling
Own modules
More about Python's features
Few words about the exam