표준입출력
print('python','java',sep=",",end="?")
print('무엇이 더 재밌을까요???')
import sys
print('python','java',file = sys.stdout) #표준 출력으로 처리
print('python','java',file = sys.stderr) #표준 에러로 처리
#시험 성적
scores = {"수학":0,"영어":50,"코딩":100}
#items()는 키 벨류 쌍으로 튜플로 보내줌
#정형화된 포맷으로 출력하기
for subject,score in scores.items():
#print(subject,score)
print(subject.ljust(8),str(score).rjust(4),sep=":" ) #subject 왼쪽으로 정렬을 하되 8글자의 공간을 확보해달라는 의미
#score 오른쪽으로 공간 4개주고 정렬
#은행 대기 순번표 001 002 003 0채우기
for num in range(1,21):
print('대기번호:'+str(num).zfill(3))
# zfill(n) n번자리를 주고 남는 앞자리 0으로채움
answer = input("아무 값이나 입력하세요: ")
print(type(answer))
print("입력하신 값은 "+answer +"입니다.")
다양한 출력포맷
# 빈 자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 10자리 공간을 확보
print("{0: >10}".format(500))
#양수일땐 +로 표시 ,음수일 땐 -로 표시
print("{0: >+10}".format(500))
print("{0: >+10}".format(-500))
#왼쪽 정렬하고, 빈칸을 _로 채움
print("{0:_<+10}".format(400))
#3자리 마다 콤마를 찍어주기
print("{0:,}".format(100000000000000))
#3자리 마다 콤마를 찍어주기 , +,-부호도 추가하기
print("{0:+,}".format(100000000000000))
print("{0:+,}".format(-100000000000000))
# 빈자리 웃는표시로 채우기 , 왼쪽정렬하고 +-부호도 붙이고 3자리마다 콤바도 찍어주기
print("{0:^<+30,}".format(100000000000000))
#소수점 출력
print("{0:f}".format(5/3))
#소수점 특정 자리수 까지만 표시!
print("{0:.2f}".format(5/3))
파일입출력
#파일 쓰기
score_file = open("score.txt","w",encoding="utf8") #파일을 쓸때 w 인코딩은 utf-8로
print("수학 : 0",file=score_file)
print("영어 : 50",file=score_file)
score_file.close()
#파일 이어쓰기
score_file = open("score.txt","a",encoding="utf8") # 기존에 있는파일에 이어쓰기 append의 a
score_file.write("과학 :80")
score_file.write("\\n코딩 :100")
#파일 읽어오기
score_file = open("score.txt","r",encoding="utf8")
print(score_file.read())
score_file.close()
#한줄 한줄 불러서 처리하고 싶을 때
score_file = open("score.txt","r",encoding="utf8")
print(score_file.readline(),end="") #줄별로 읽기,한줄 읽고 커서는 다음 줄로 이동
print(score_file.readline(),end="")
print(score_file.readline(),end="")
print(score_file.readline(),end="")
score_file.close()
#파일이 총 몇 줄 인지 모를떄
score_file = open("score.txt","r",encoding="utf8")
while True:
line = score_file.readline()
if not line:
break
print(line,end="")
score_file.close()
#리스트에 값을 다 넣고 처리할때
score_file = open("score.txt","r",encoding="utf8")
lines = score_file.readlines() #list형태로 저장
for line in lines:
print(line,end="")
score_file.close()
pickle
# Pickle 사용하는데이터를 파일형태로 저장하는 것
import pickle
#쓰기
profile_file = open("profile.pickle","wb") #파일을 열땨는 쓰기(w) 목적으로 바이너리타입 정의(b)
profile = {"이름":"박명수","나이":30,"취미":["축구","골프","코딩"]}
print(profile)
pickle.dump(profile, profile_file) #profile에 있는 정보를 file 에 저장
profile_file.close()
#읽기
profile_file = open("profile.pickle","rb") #파일을 열땨는 쓰기(w) 목적으로 바이너리타입 정의(b)
profile = pickle.load(profile_file)
print(profile)
profile_file.close()
with
import pickle
with open ("profile.pickle","rb") as profile_file: # 파일정보를 profile_file이라는 변수에 저장
print(pickle.load(profile_file))
# with 문은 close()필요없이 불러온 파일을 자동으로 종료시켜준다
#pickle이 아닌 일반적인 파일입출력 with as문 사용
with open("study.txt","w",encoding="utf8") as study_file:
study_file.write("파이썬을 열심히 공부하고 있어요")
with open("study.txt","r",encoding="utf8") as study_file:
print(study_file.read())