python

Files and Exceptions

Chan Lee 2025. 2. 10. 16:52

Files and Exceptions

 

 

To access a file, you must first open it

Open a file for reading (“r”)

 

Open a file for writing (“w”)

 

 - If the output file already exists, it is emptied before the new data is written into it.

 - If the file does not exist, an empty file is created.

 

To write in the file, 

 - You MUST explicitly write the newline character (\n) to start a new line.

 - You can also write formatted strings to a file with the write method.

 

If you need to process a file written in other than ASCII characters, you need to:

infile = open(“input.txt”, “r”, encoding=“utf-8”)

outfile = open(“output.txt”, “w”, encoding=“utf-8”)

 

To read a single line,

 

ex) 




Exception Handling

exception handler: A sequence of statements that is given control when an exception of a particular type has been thrown and caught.

 

Raise Exception 

 

Try/Except Statement

 

Occasionally, you need to take some action whether or not an exception is raised. The finally construct is used to handle this situation.

 

Because a try/finally statement for opening and closing files is so common, 
Python has a special shortcut:

This with statement opens the file with the given name, sets outfile to the file object, and closes the file object when the end of the statement has been reached or an exception was raised.

 

* To make a function as portable as possible, the exceptions are better handled in the main function.