Chapter 8.
Python Files
2023-2024
COMP1117A Computer Programming
Dr. T.W. Chim ([email protected]) & Dr. H.F. Ting ([email protected])
Department of Computer Science, The University of Hong Kong
File I/O
Read lines from disk file
Each iteration i will be
referring to a line in the file
“testfile.txt”
Note: it gives the whole line,
including the end-of-line char
(‘\n’). That is, for the 1st
Since the default end symbol is ‘\n’, 2 end-of-line characters iteration,
are printed after each line. i = “This is the first line\n”
3
Read lines from disk file
Recall that this method will
remove all leading and tailing
whitespaces.
4
Write to a file
if just a file name, the file
Can be any valid
will be created in the same
name you like
folder as the program
fout = open(“D:/COMP1117/output.txt”, “w”) If not in the same
folder, you should
give the whole path.
Remember to use /
instead of \.
5
Write to a file
If “output.txt” does not exist, the
system will create an empty file for
you. If it already exists, the system will
first erase all its content.
6
Write a string
You MUST close the file
when you no longer use
it; otherwise, the strings
will not be written.
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
More Python exceptions can be found at:
https://docs.python.org/3/library/exceptions.html
16
Chapter 8.
END
2023-2024
COMP1117A Computer Programming
Dr. T.W. Chim ([email protected]) & Dr. H.F. Ting ([email protected])
Department of Computer Science, The University of Hong Kong