2023. 10. 24. 18:12ㆍ프로그래밍 공부/Python
MOTIVATION
저장 기술의 종류
| Storage Technology | Example | Charateristics |
| Magnetic Storage | Hard drive | Nonvolatile |
| Magnetic Tape Storage | Nonvolatile | |
| Semiconductor Memory | Main Memory | Volatile |
| USB (Thumb) Drive | Nonvolatile | |
| Optical Storage | CD, DVD | Nonvolatile |
FUNDAMENTAL CONCEPTS
8.1 텍스트 파일이란?
텍스트 파일(text file): 문자를 포함하는 파일로 텍스트의 행으로 구성된다.
바이너리 파일(binary file): 컴퓨터 프로그램만이 읽을 수 있는 형태로 포맷된 파일
8.2 텍스트 파일 이용하기
8.2.1 텍스트 파일 열기
모든 파일을 사용하기 전에 먼저 파일을 열어야 한다.
파이썬에서는 파일을 열면 파일에 접근하는 방법을 제공하는 파일 객체가 만들어진다.
읽기를 위한 열기
input_file = open('myfile.txt','r')
Python에서 읽기 위해 파일을 열기 위해, (선택 사항) 인수 값 'r'을 사용하여 열린 내장 함수를 호출한다.
파일 위치의 상대 경로
input_file = open('data/myfile.txt','r')
파일 위치의 절대 경로
input_file = open('C:/mypythonfiles/data/myfile.txt','r')
파일 닫기
input_file.close()
쓰기를 위한 열기
output_file = open('mynewfile.txt','w')
이 경우 'w'는 파일이 쓰기 위해 열려야 함을 나타낼 때 사용된다.
파일이 이미 존재하는 경우 덮어쓰기된다(파일의 첫 번째 줄부터 시작).
두 번째 인수에 'a'를 사용할 때 대신에 출력이 기존 파일에 추가된다.
파일 닫기
output_file.close()
8.2.2 텍스트 파일 읽기
readline 메소드는 줄 끝 문자를 포함하여 텍스트 파일의 다음 줄을 반환한다.
파일 끝에 있는 경우 빈 문자열이 반환된다.
예시)
TextFile myfile.txt
Line One
Line Two
Line Three
input_file = open('myfile.txt','r')
empty_str = ''
line = input_file.readline()
while line != empty_str:
print(line)
line = input_file.readline()
input_file.close()
Screen Output
Line One
Line Two
Line Three
8.2.3 텍스트 파일 쓰기
write() 메서드를 사용하여 파일에 텍스트를 출력한다.
모든 데이터가 작성되었는지 확인하려면 close() 메서드를 호출하여 모든 정보가 작성된 후 파일을 닫는다.
예시)
TextFile myfile.txt
Line One
Line Two
Line Three
empty_str = ''
input_file = open('myfile.txt','r')
output_file = open('myfile_copy.txt','w')
line = input_file.readline()
while line != empty_str:
output_file.write(line)
line = input_file.readline()
output_file.close()
Screen Output
line one
line two
line three
8.3 문자열 처리
문자열 처리(string processing): 문자열에 액세스, 분석 및 업데이트할 수 있도록 하는 작업
8.3.1 문자열 순회
for문의 for chr in string 형식을 사용하여 명시적 인덱스 변수를 사용하지 않고 문자열의 문자를 쉽게 이동할 수 있다.
예시)
space = ' '
num_spaces = 0
line = input_file.readline()
for k in range(0,len(line)):
if line[k] == space:
num_spaces = num_spaces + 1
마지막 3줄을 for chr in string 형식을 이용하여 다음과 같이 변경 가능하다.
for chr in line:
if chr == space:
num_spaces = num_spaces + 1
8.3.2 문자열에 적용가능한 시퀀스 작업
| Length | len(str) | Membership | 'h' in s |
| Select | s[index_val] | Concatenation | s + w |
| Slice | s[start:end] | Minimum Value | min(s) |
| Count | s.count(char) | Maximum Value | max(s) |
| Index | s.index(char) | Comparison | s == w |
문자열은 불변이기 때문에 시퀀스 수정 연산은 적용되는 문자열을 수정하지 않는다.
오히려 원본의 수정된 버전인 새로운 문자열을 생성한다.
8.3.3 문자열 메소드
| Checking the Contents of a String | |||
| str.isalpha() | Returns True if str contains only letters. |
s = 'Hello' | s.isalpha() -> True |
| s = 'Hello!' | s.isalpha() -> False | ||
| str.isdigit() | Returns True if str contains only digits. |
s = '124' | s.isdigit() -> True |
| s = '124A' | s.isdigit() -> False | ||
| str.islower() str.isupper() |
Returns True if str contains only lower (upper) case letters. |
s = 'hello' | s.islower() -> True |
| s = 'Hello' | s.isupper() -> False | ||
| str.lower() str.upper() |
Returns lower(upper) case version of str. |
s = 'Hello!' | s.lower() -> 'hello!' |
| s = 'hello!' | s.upper() -> 'HELLO!' | ||
| Searching the Contents of a String | |||
| str.find() | Returns the index of the first occurence of w in str. Return -1 if not found. | s = 'Hello!' | s.find('l') -> 2 |
| s = 'GoodBye' | s.find('l') -> -1 | ||
| Replacing the Contents of a String | |||
| str.replace(w, t) | Returns a copy of str with all occurences of w replaced with t. | s = 'Hello!' | s.replace('H', 'J') -> 'Jello' |
| s = 'Hello' | s.replace('ll', 'r') -> 'Hero' | ||
| Removing the Contents of a String | |||
| str.strip(w) | Returns a copy of str with all leading and trailing characters that appear in w removed. | s = ' Hello! ' s = 'Hello\n' |
s.strip(' !') -> 'Hello' s.strip('\n') -> 'Hello' |
| Splitting a String | |||
| str.split(w) | Returns a list containing all strings in str delimited by w. | s = 'Lu, Chao' | s.split(',')-> ['Lu', 'Chao'] |
문자열의 내용 확인하기
Python은 일반적인 시퀀스 연산 외에도 문자열에 특화된 여러 가지 메소드를 제공한다.
문자열 탐색과 수정
Python에서 find, replace, 그리고 strip 메소드는 수정된 문자열을 검색하고 생성하는 데 사용될 수 있다.
8.4 예외 처리
8.4.1 예외란?
예외(exception): 함수 자체가 처리할 수 없는 예기치 않은 또는 "예외적인" 상황이 발생했음을 나타내는 함수에 의해 "높아진" 값(개체)
파이썬에서의 몇몇 표준 에러
| ImportError | raised when an import (or from ... import) statement fails |
| IndexError | raised when a sequence index is out of range |
| NameError | raised when a local or global name is not found |
| TypeError | raised when an operation or function is applied to an object of inappropriate type |
| ValueError | raised when a built-in operation or function is applied to an appropriate type, but of inappropriate value |
| IOError | raised when an input/output operation fails (e.g., "file not found") |
8.4.2 예외 발생의 전파
예외는 클라이언트 코드에 의해 처리되거나 처리될 때까지 클라이언트의 호출 코드로 자동 전파되는 등의 방식으로 처리된다.
예외가 메인 모듈(처리되지 않고)까지 다시 던져지면 프로그램은 예외의 세부 정보 표시를 종료한다.
8.4.3 예외 포착과 처리
예외는 try 블록과 예외 처리기를 사용하여 Python에서 포착하고 처리한다.
예외 처리를 통한 프로그램 복구 예시)
import math
num = int(input('Enter number to compute factorial of: '))
valid_input = False
while not valid_input:
try:
result = math.factorial(num)
print(result)
valid_input = True
except ValueError:
print('Cannot compute factorial of negative numbers')
num = int(input('Please re-enter: '))
Enter number to compute factorial of: -5
Cannot compute factorial of negative numbers
Please re-enter: 5
120
8.4.4 예외 처리와 사용자 입력
프로그래머 정의 함수는 파이썬의 내장 함수에 의해 발생하는 예외 외에도 예외를 일으킬 수 있다.
예시)
def getMonth():
month = int(input('Enter current month (1-12): '))
if month < 1 or month > 12:
raise ValueError('Invalid Month Value')
return month
valid = False
while not valid:
try:
month = getMonth()
valid = True
except ValueError as err_msg:
print(err_msg, '\n')
8.4.5 예외 처리와 파일 처리
파일 열기 오류로 인해 발생한 IOError 예외를 포착하여 처리할 수 있다.
예시)
file_name = input('Enter file name: ')
empty_str = ''
input_file_opened = False
while not input_file_opened:
try:
input_file = open(file_name, 'r')
input_file_opened = True
line = input_file.readline()
while line != empty_str:
print(line.strip('\n')
line = input_file.readline()
except IOError:
print('File Open Error\n')
file_name = input('Enter file name: ')
'프로그래밍 공부 > Python' 카테고리의 다른 글
| 10 객체 지향 프로그래밍 (0) | 2023.10.24 |
|---|---|
| 9 딕셔너리와 세트 (0) | 2023.10.24 |
| 7 모듈러 디자인 (1) | 2023.10.23 |
| 6 객체와 사용 (0) | 2023.10.23 |
| 5 함수 (0) | 2023.10.23 |