(파일 객체) = open('파일경로', '읽기모드')
(파일 객체).close()
# 방법1) write()
(파일 객체).write('내용')
# 방법2) print()
print('내용', file=(파일객체))
def readline_test1():
my_file = open('myfile.txt', 'r')
line = my_file.readline().rstrip()
while line:
print(line)
line = my_file.readline().rstrip()
my_file.close()
def read_using_for():
my_file = open('myfile.txt', 'r')
for line in my_file: # for line in list(my_file)도 가능
print(line.rstrip()
my_file.close()
def readlines_test():
my_file = open('myfile.txt', 'r')
lst = my_file.readlines()
for line in lst:
print(line.rstrip())
def read_test():
my_file = open('myfile.txt', 'r')
s = my_file.read()
for line in f:
print(line.rstrip())
with()키워드 사용with open('파일명', '모드') as (파일 객체):
문장
이름, 키, 몸무게
김철수, 176, 62
이영희, 155, 49
# weather.csv 파일은 20년 동안 매일 모 강의실의 기온이 측정된 파일 자료
def without_csvModule():
with open("weather.csv", "rt") as f:
temp = 100
f.readline()
line = f.readline()
while line:
line = line.split(',')
if temp > float(line[3]):
temp = float(line[3])
line = f.readline()
print('가장 추운 날의 기온', temp)
def q4_w_csv():
import csv
with open('weather.csv', 'rt') as f:
data = csv.reader(f) # readline()을 이용하는 것과 동일
next(data) # 다음 번째 line을 읽어옴
temp = 100
for line in data:
if temp > float(line[3]):
temp = float(line[3])
print('가장 추운 날의 기온', temp)
def bin_write():
# 바이너리 파일에 0부터 255까지 값 작성
# read(바이트수) // write(바이트리스트)
with open('test.bin', 'wb') as f:
lst = bytes(list(range(256)))
f.write(lst)
def cpy_img():
# 원본 열기 -> 닫기
# 복사본 열기 -> 닫기
# 원본 내용이 있을 동안 원본에서 1024바이트 읽어와서 그대로 복사본에 쓰기
with open ('pic.jpeg', 'rb') as org: # b 빼먹으면 아무것도 안보임
with open('pic_cpy.jpeg', 'wb') as cpy:
buf = org.read(1024)
while buf:
cpy.write(buf)
buf = org.read(1024)
SyntaxError: EOL while scanning string literal
예외 발생 코드
number_input_a = int(input('정수 입력 >'))
print("원의 반지름:", number_input_a)
print("원의 둘레:", 2 * 3.14 * number_input_a)
print("원의 넓이:", 3.14 * number_input_a**2)
사용자가 정수를 입력하지 않았을 때 발생하는 예외
정수입력 > 7센티미터
Traceback (most recent call last):
File "test.py", line 2, in <module>
number_input_a = int(input('정수 입력 > '))
ValueError: invalid literal for int() with base 10: '7센티미터'
user_input_a = input('정수 입력 > ')
if user_input_a.isdigit():
number_input_a = int(user_input_a)
print("원의 반지름:", number_input_a)
print("원의 둘레:", 2 * 3.14 * number_input_a)
print("원의 넓이:", 3.14 * number_input_a**2)
else:
print("정수를 입력하지 않았습니다.")
기본 형태
try:
예외가 발생할 가능성이 있는 코드
except: # 오류 입력 안할 시 전체 오류에 대해 탐지
예외가 발생했을 때 실행할 코드
예제
try:
number_input_a = int(input('정수 입력 >'))
print("원의 반지름:", number_input_a)
print("원의 둘레:", 2 * 3.14 * number_input_a)
print("원의 넓이:", 3.14 * number_input_a**2)
except:
print("에러 발생!")
try:
예외가 발생할 가능성이 있는 코드
except (예외 객체) as (예외 객체를 활용할 변수 이름): # 오류 입력 안할 시 전체 오류에 대해 탐지
예외가 발생했을 때 실행할 코드
list_number = [52, 273, 32, 72, 100]
try:
numper_input = int(input("정수 입력 > "))
print(f'{number_input}번째 요소: {list_number[number_input]}')
except ValueError as exception:
print("정수를 입력해주세요!")
print(type(exception), exception)
except IndexError as exception:
print("리스트의 인덱스를 벗어났어요!")
print(type(exception), exception)
except Exception as exception:
print("미리 파악하지 못한 예외가 발생했습니다.")
print(type(exception), exception)
raise (예외 객체)
number = input("정수 입력 > ")
number = int(number)
if number > 0:
raise NoyImplementedError
else:
raise NotImplementedError