Python
Python 문법 기초 31 - file i/o (try ~ except) + pickle(import)
코딩탕탕
2022. 10. 22. 17:27
# file i/o
import os
print(os.getcwd())
try:
print('읽기') # 읽기
# f1 = open(r'C:\work\psou\pro1\pack3/file_test.txt', mode = 'r', encoding = 'utf8')
# f1 = open(os.getcwd() +'\\file_test.txt', mode = 'r', encoding = 'utf8')
f1 = open('file_test.txt', mode = 'r', encoding = 'utf8') # mode = 'r', 'w', 'a', 'b' ...
print(f1.read())
f1.close()
print('저장') # 덮어쓰기
f2 = open('file_test2.txt', mode = 'w', encoding = 'utf8')
f2.write('My friends\n')
f2.write('홍길동, 나길동')
f2.close()
print('추가') # 추가
f3 = open('file_test2.txt', mode = 'a', encoding = 'utf8')
f3.write('\n손오공')
f3.write('\n팔계')
f3.write('\n오정')
f3.close()
print('읽기')
f4 = open('file_test2.txt', mode = 'r', encoding = 'utf8')
print(f4.readline()) # 한줄씩 읽는다
print(f4.readline())
f4.close()
except Exception as e:
print('에러 : ', e)
<console>
C:\work\psou\pro1\pack3
읽기
가을이 깊어가고
파이썬도 깊어가고
DB연동
프로그램이
서서히 다가오고 있다
저장
추가
읽기
My friends
홍길동, 나길동
read()는 내용을 읽어주는 함수이다.
readline() 은 한 줄씩 읽어주는 함수이다.
close()는 open() 했으면 무조건 닫아야 된다.
파일이 없다면 만들어진다.
mode 종류
파일열기모드 설명
| r | 읽기모드 - 파일을 읽기만 할 때 사용 |
| w | 쓰기모드 - 파일에 내용을 쓸 때 사용 |
| a | 추가모드 - 파일의 마지막에 새로운 내용을 추가 시킬 때 사용 |
| t | 텍스트 모드, 텍스트 문자 기록에 사용 (디폴트) |
| b | 바이너리 모드, 바이트단위 데이터 기록에 |
| wb | 바이너리 쓰기모드 |
| rn | 바이너리 읽기모드 |
# file i/o + with 문
try:
# 저장
with open('file_test3.txt', mode = 'w', encoding='utf8') as obj1:
obj1.write('파이썬으로 문서 저장\n')
obj1.write('with문을 쓰면\n')
obj1.write('명시적으로 close()를 하지 않는다.')
# 읽기
with open('file_test3.txt', mode = 'r', encoding='utf8') as obj2:
print(obj2.read())
except Exception as e:
print('오류 : ', e)
print('피클링(객체 저장)')
import pickle
try:
dictData = {'소현' : '111-1111', '승경' : '222-2222'}
listData = ['곡물그대로리', '새우깡']
tupleData = (listData, dictData) # 복합 객체
# 객체를 저장
with open('hello.dat', mode = 'wb') as obj3:
pickle.dump(tupleData, obj3) # data, 파일객체
pickle.dump(listData, obj3)
# 객체를 읽기
with open('hello.dat', mode = 'rb') as obj3:
a, b = pickle.load(obj3)
print(a)
print(b)
c = pickle.load(obj3) # 변수가 하나이므로 listData밖에 안 담긴다.
print(c)
except Exception as e2:
print('오류 : ', e2)
with문을 사용하면 close()를 할 필요가 없다.
경로가 현재경로이면 open() 시 바로 이름명을 입력하면 된다.
예제 1) 동 이름을 입력해 해당 동 관련 우편번호 및 주소 출력
# 동 이름을 입력해 해당 동 관련 우편번호 및 주소 출력
try:
# dong = input('동 이름 입력 :')
# print(dong)
dong = '개포'
with open('zipcode.txt', mode = 'r', encoding = 'euc-kr') as f:
line = f.readline()
# print(line)
# lines = line.split('\t') 같은 의미이다.
lines = line.split(chr(9))
# print(lines)
if lines[3].startswith(dong):
# print(lines)
print('[' + lines[0] + ']' + lines[1] + ' ' + lines[2] + ' ' + lines[3] + ' ' + lines[4])
except Exception as e:
print('err : ', e)
<console>
[135-806]서울 강남구 개포1동 경남아파트
우편번호가 들어있는 txt 파일을 미리 준비해둔 상태이다.
# 동 이름을 입력해 해당 동 관련 우편번호 및 주소 출력
try:
dong = input('동 이름 입력 :')
print(dong)
with open('zipcode.txt', mode = 'r', encoding = 'euc-kr') as f:
line = f.readline()
# print(line)
while line:
# lines = line.split('\t') 같은 의미이다.
lines = line.split(chr(9))
# print(lines)
if lines[3].startswith(dong):
# print(lines)
print('[' + lines[0] + ']' + lines[1] + ' ' + lines[2] + ' ' + lines[3] + ' ' + lines[4])
line = f.readline()
except Exception as e:
print('err : ', e)
<console>
동 이름 입력 :청담동
청담동
[135-766]서울 강남구 청담동 금하빌딩
[135-765]서울 강남구 청담동 세신빌딩
[135-762]서울 강남구 청담동 에버원메디컬리조트
[135-767]서울 강남구 청담동 오미빌딩
[135-763]서울 강남구 청담동 은성빌딩
[135-761]서울 강남구 청담동 정화빌딩
[135-764]서울 강남구 청담동 청담빌딩
[135-948]서울 강남구 청담동 1∼5
[135-949]서울 강남구 청담동 6∼19
[135-950]서울 강남구 청담동 20∼35
[135-951]서울 강남구 청담동 36∼47
[135-952]서울 강남구 청담동 48∼61
[135-953]서울 강남구 청담동 62∼76
[135-954]서울 강남구 청담동 78∼91
[135-517]서울 강남구 청담동 92∼99
[135-956]서울 강남구 청담동 100∼106
[135-955]서울 강남구 청담동 107∼123
[135-957]서울 강남구 청담동 124∼132
[135-958]서울 강남구 청담동 133∼134
[135-959]서울 강남구 청담동 135∼143
[135-100]서울 강남구 청담동
while 문으로 해당 동은 다 출력한다.
조건과 while문을 빼고 read()로 하면 모든 데이터 출력 가능

최소한 체크 된 곳 정도는 알아두자.