728x90
In [1]:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
#티스토리 업로드 원활하게:-)
10. 파일 입출력과 예외처리¶
In [27]:
# 291 파일 쓰기
f = open("C://Users/Admin/desktop/매수종목1.txt",mode="w",encoding="utf-8")
f.write("005930\n")
f.write("005380\n")
f.write("035420\n")
f.close()
In [26]:
# 292 파일 쓰기
f = open("C://Users/Admin/desktop/매수종목2.txt","w",encoding="utf8")
f.write("005930 삼성전자\n")
f.write("005380 현대차\n")
f.write("035420 NAVER\n")
f.close()
In [29]:
# 파일명만 다르게 위와 같은 식 구현함
f = open("C://Users/Admin/desktop/매수종목2_1.txt","w",encoding="utf8")
a= ["005930 삼성전자\n","005380 현대차\n""035420 NAVER\n"]
f.writelines(a)
f.close()
In [17]:
# 293 CSV 파일 쓰기
import csv
f = open("C://Users/Admin/desktop/매수종목.csv","w",encoding="cp949",newline="")
fw= csv.writer(f)
fw.writerow(["종목명","종목코드","PER"])
fw.writerow(["삼성전자","005930",15,59])
fw.writerow(["Naver","035420",55.82])
f.close()
In [24]:
# 294 파일 읽기
f = open("C://Users/Admin/desktop/매수종목1.txt",mode="r",encoding="utf8")
lines = f.readlines()
code_list =[]
for i in lines:
code = i.strip()
code_list.append(code)
print(code_list)
f.close()
['005930', '005380', '035420']
In [31]:
# 295 파일 읽기
f= open("C://Users/Admin/desktop/매수종목2.txt","r",encoding="utf8")
lines = f.readlines()
code_dict={}
for i in lines:
i = i.strip() #줄바꿈 지우기
key, value = i.split() #공백기준으로 분리하기
code_dict[key]=value
print(code_dict)
f.close()
{'005930': '삼성전자', '005380': '현대차', '035420': 'NAVER'}
In [36]:
# 296 예외처리
# 에러가 발생하는 PER은 0으로 출력
per = ["10.31", "", "8.00"]
for i in per:
try:
print(float(i))
except:
print(0)
10.31
0
8.0
In [38]:
# 297 예외처리 및 리스트에 저장
per = ["10.31", "", "8.00"]
new_per=[]
for i in per:
try:
new_per.append(float(i))
except:
new_per.append(0)
print(new_per)
[10.31, 0, 8.0]
In [48]:
# 298 특정 예외만 처리하기
def zero(x):
try:
x/0
except ZeroDivisionError:
return print("ZeroDivisionError 에러")
In [49]:
print(zero(4))
ZeroDivisionError 에러
None
In [54]:
# 299 예외의 메시지 출력하기
data = [1, 2, 3]
In [58]:
for i in range(5):
try:
print(data[i])
except IndexError as xx:
print(xx)
1
2
3
list index out of range
list index out of range
In [60]:
# 300 try, except, else, finally 구조 사용해보기
per = ["10.31", "", "8.00"]
for i in per:
try:
print(float(i))
except :
print("Error")
else:
print("에러 안났다!")
finally:
print("에러가 났든말든")
10.31
에러 안났다!
에러가 났든말든
Error
에러가 났든말든
8.0
에러 안났다!
에러가 났든말든
728x90
'😁 빅데이터 문제 풀기 & Study > - 이외 사이트 문제' 카테고리의 다른 글
[Pandas] Pandas 연습 문제 풀기 - 1 🐼 (0) | 2022.02.21 |
---|---|
초보자를 위한 파이썬 300제 (241~290번) 10. 파이썬 모듈/11. 파이썬클래스 (0) | 2022.01.10 |
초보자를 위한 파이썬 300제 (201~240번) 9. 파이썬 함수 (0) | 2022.01.07 |
초보자를 위한 파이썬 300제 (131~200번) 8. 파이썬 반복문 (0) | 2022.01.07 |
초보자를 위한 파이썬 300제 (101~130번) 7. 파이썬 분기문 (0) | 2022.01.07 |