본문 바로가기
Language/Python

[Python] Except / File

by 별토끼. 2017. 8. 17.
반응형

[Python] Except / File

  • Except

 - except 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#-*- coding: utf-8 -*-
'''
'''
 
try:
    num1 = input("젯수 입력:")
    num2 = input("피젯수 입력:")
    print num2,"를", num1, "으로 나눈값:", num2/num1
except ZeroDivisionError as zde:
    print "어떤수를 0으로 나눌수는 없습니다.", zde
except Exception as e:
    print "알수 없는 에러 발생!", e
else:
    print "오류없이 수행되었습니다."
finally:
    print "오류발생과 상관없이 반드시 실행이 보장되는 블럭입니다."
 
print "프로그램을 마무리 합니다."
cs




  • File open/read/write
 - 2 : 파일 경로 구성을 위해서는 os를 import해야한다.
 - 5 : 현재 작업 디렉토리 - os.getcwd() =currentWorkDirectory=경로
 - 6 : 파일 구분자 - os.sep = /
 - 13 : 파일 열기 - codecs.open(파일경로, 모드, 인코딩)
 - 15 : result = f.read()
 - 22 : .write() = 파일에 문자열 기록하기
 - 23 : close하는 순간 파일이 만들어진다.
 - 34 : readline() - 한줄씩 읽어온다.
 - 41 : readlines() - 한줄씩읽어서 list에 리턴해준다.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#-*- coding: utf-8 -*-
import os
import codecs
 
print u"현재 작업 디렉토리:", os.getcwd()
print u"현재 플렛폼의 파일 구분자:", os.sep
 
try:
    #읽어올 파일 경로 구성하기 (getCurrentWorkDirectory)
    filePath = os.getcwd()+os.sep+"testFile.txt"
    print filePath
    #파일 열기 .open(파일경로, 모드, 인코딩)
    f=codecs.open(filePath, "r""utf-8"#읽기 모드
    #텍스트 문서의 내용 읽어들이기
    result=f.read()
    print result
    f.close()
    
    #파일을 만들어서 문자열 기록하기
    letterPath=os.getcwd()+os.sep+"testFile2.txt"
    letter=codecs.open(letterPath,"w","utf-8")
    letter.write(u"To my Friend ~")
    letter.close() #close() 하는 순간 파일이 만들어 진다.
    
    #파일을 열어서 문자열 추가하기
    letter2=codecs.open(letterPath, "a","utf-8"# 추가 모드
    for i in range(10):
        letter2.write(u"\n안녕하세요")
    letter2.close()
    
    print u".readline() 테스트"
    letter3=codecs.open(letterPath,"r","utf-8")
    #한줄씩 읽어와서 출력하기
    print letter3.readline()
    print letter3.readline()
    letter3.close()
    
    print u".readlines() 테스트"
    letter4=codecs.open(letterPath,"r","utf-8")
    #한줄씩 읽은 데이터를 list에 담아서 리턴해준다.
    lines=letter4.readlines()
    #반복문 돌면서 출력하기
    for item in lines:
        print item
except Exception as e:
    #예외가 발생했을 때 실행되는 블럭
    print(e)
except Exception as e:
    #예외가 발생했을 때 실행되는 블럭
    print(e)
cs





  • File에서 search 이용하기
 - 07 : split - 문자열 나누기 (tab을 기준으로 문자를 나누어 result에 저장한다
 - 40 : tab을 기준으로 나누어 문자열을 저장한다.
 - 43 : search(입력받은문자, 기존정보) = 문자열 전체를 검색하여 정규식과 매치되는지 조사한다.
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#-*- coding: utf-8 -*-
import re
import os
import codecs
 
sample = u"a b c ddd    eee"
result=re.split(r"[\t]+",sample)
 
print result
 
cwd=os.getcwd()
filePath=cwd+os.sep
filePath=cwd+os.sep+"testFile.txt"
f=codecs.open(filePath,"r","utf-8")
 
while True:
    data=f.readline()
    if data=="":
        break #반복문 블럭 빠져 나오기
    print data
    
# 위의 예제를 참고해서 검색어를 입력받아서
inputKeyword=raw_input("검색할 동,면,리 입력:")
decodedKeyword=inputKeyword.decode("utf-8")
 
# 해당 검색어에 관련된 모든 주소를 출력해 보세요.
 
    
# 파일 열기
zipPath=os.getcwd()+os.sep+"zipcode.txt"
zipFile=codecs.open(zipPath,"r","utf-8")
print u"검색중.."
 
while True:
    #한줄씩 읽어온다.
    data=zipFile.readline()
    if data=="":
        break
    # 한 줄의 정보를 list type으로 받아온다.
    info=re.split(r"[\t ]+", data)    
    
    # 배열의 3번째 방에 입력한 키워드가 존재하는지 여부
    result = bool(re.search(decodedKeyword, info[3]))
    if result:
        print data
zipFile.close()
 
# 파일 열기
zipFile=codecs.open(zipPath,"r","utf-8")
# 동을 입력하면 우편번호를 출력해보세요
inputKeyword=raw_input("우편번호를 알고 싶은 동 입력:")
decodedKeyword=inputKeyword.decode("utf-8")
print "검색중..."
 
while True:
    data=zipFile.readline()
    if data=="":
        break
    info=re.split(r"[\t ]+", data)
    result = bool(re.search(decodedKeyword, info[3]))
    if result:
        print decodedKeyword," 의 우편번호:", info[0]
zipFile.close()
 
cs



반응형

'Language > Python' 카테고리의 다른 글

[Python] Object Oriented Programming  (0) 2019.08.14
0710 Python 문법, 우분투 사용법  (0) 2019.07.10
[Python] Decorator  (0) 2017.08.16
[Python] Extends / super  (0) 2017.08.16
[Python] Main / class / 생성자 / return  (1) 2017.08.16

댓글