Chapter 8 PythonFiles
Chapter 8 PythonFiles
Python Files
2023-2024
COMP1117A Computer Programming
Dr. T.W. Chim (twchim@cs.hku.hk) & Dr. H.F. Ting (hfting@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
File I/O
Read lines from disk file
4
Write to a file
6
Write a string
7
Write a line
8
Append strings to a file
Recall that the “w” option will erase the file content if it exists.
If you want to keep the old content of the file, and just want to
append strings after them. You may use the “a” option.
9
Exception
Handling
Catching exceptions
A lot of things can go wrong when reading/writing a file.
For example
The file you want to read does not exist.
Your program does not have permission to write.
The path you specify is in fact a folder.
11
Catching exceptions
Thus, it is better to “try” first.
The statement “try: .... except:...” will first try to execute the “body” of try, and if
there is any error in the execution, it will execute the “body” of except.
Then, it will execute the following statement (regardless of whether there is error
during the execution of the body of try.
12
Catching exceptions
Although the following program uses “try:... except:…” to
detect file opening error, but it will still get into “system error”
trouble if you read a wrong file.
13
Catching exceptions
The following program avoids the “system error” message.
14
Catching other exceptions
The following program catches invalid input exception.
15
Catching more exceptions
END
2023-2024
COMP1117A Computer Programming
Dr. T.W. Chim (twchim@cs.hku.hk) & Dr. H.F. Ting (hfting@cs.hku.hk)
Department of Computer Science, The University of Hong Kong