[패스트캠퍼스 수강 후기] 파이썬 인강 100% 환급 챌린지 26 회차 미션

2020. 11. 27. 23:49Coding/Python-Fastcampus

728x90

09. 파일 - 02. 파일 읽기, 파일 쓰기(2)

 

/resource/score.txt

1
2
3
4
5
6
95
78
92
89
100
66
cs

 

section09.py

1
2
3
4
5
6
7
8
9
10
11
12
13
with open('./resource/score.txt''r'as f :
 
    line = f.readline()
    num = 0
    total = 0
    while line :
        num += 1
        total += int(line)
        
        print(line.strip(), total)
        line = f.readline()
    
    print('avg = ', total / num)
cs

score에 있는 숫자의 평균을 구하는건데, 생각나는데로 이렇게 풀었지만....

 

1
2
3
4
5
6
with open('./resource/score.txt''r'as f:
    score = []
    for line in f:
        score.append(int(line))
    print(score)
    print('Average : {:6.3f}'.format(sum(score) / len(score)))
cs

이렇게 간단한 방법이 있더라...

 

 


파일쓰기.

1
2
3
4
5
6
with open('./resource/test.txt''w'as f:
    f.write('파일 쓰기!')
 
 
with open('./resource/test.txt''a'as f:
    f.write('기존 파일에 추가!!')
cs

w는 새로운 파일을 만들기 때문에, 기존에 파일이 있으면 기존 내용을 없애고 새로 만든다.

a는 기존에 파일에 추가해서 내용을 넣지만, 기존 파일이 없는 경우 파일을 생성한다.

 

 

 

 


10. 예외 - 01. 에러 및 예외 처리(1)

NameError.

1
2
3
4
= 10
= 15
 
print(c)
cs

이렇게 틀리지는 않겠지만, 오타로 없는 변수를 찾을때

 

 

SyntaxError.

1
2
if True
   pass
cs

: 빼먹는 경우도 많겠지만, 문법이 틀린경우 자주 볼 수 있고, 뭐가 문제인지 대부분 바로 알 수 있다.

 

 

 


10. 예외 - 02. 에러 및 예외 처리(2)

try ~ except ~ finally
try 에러가 발생할 가능성이 있는 코드를 이 안에 작성.
except
except
.
.
.
except를 여러개 만들어 놓을 수 있다.
else 에러가 없을 경우 실행
finally 항상 실행

 

 

활용.
1
2
3
4
5
6
7
8
9
10
name = ['Kim''Lee''Park']
 
try:
    z = 'Lee'
    x = name.index(z)
    print('{} Found it! {} in name'.format(z, x + 1))
except ValueError:
    print('Not found it! - Occurred ValueError!')
else:
    print('else here!')
cs

 

정상.

try문이 작동하고, else문까지 정상작동을 확인.

 

에러(z = 'Li'라고 한 경우.)

except에 걸렸다.

 

 

 


어떤 에러가 올지 모를때.

1
2
3
4
5
except ValueError:
    print('Not found it! - Occurred ValueError!')
 
except:
    print('Not found it! - Occurred ValueError!')
cs

그냥 except만 적어주면 모든 에러를 검출한다.

 

 

올인원 패키지 : 파이썬 웹 개발👉https://bit.ly/33a7nvc

728x90