| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
- OOP
- string
- 반복문
- 백준
- raw data
- function
- 알고리즘
- 티스토리챌린지
- C++
- Class
- programming
- Deep Learning
- 문자열
- pass by reference
- Pre-processing
- predictive analysis
- array
- baekjoon
- 배열
- 파이썬
- assignment operator
- Object Oriented Programming
- Data Science
- const
- pointer
- vscode
- 함수
- 포인터
- Python
- 오블완
- Today
- Total
Channi Studies
Files and Exceptions 본문
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.
'python' 카테고리의 다른 글
| Iterable, Iterator, Generator (0) | 2025.02.21 |
|---|---|
| Bitwise Operators (0) | 2025.02.21 |
| Tuple 튜플 (0) | 2025.01.26 |
| List 리스트 (0) | 2025.01.26 |
| Terminating a Program (프로그램 종료) (0) | 2025.01.12 |