헬린코린이

[Python] 5일차 본문

Programming/Python

[Python] 5일차

HCD 2023. 4. 28. 23:19
# 표춘입출력 - Chapter

#sep를 붙여줌으로 문자열 사이에 어떤 값을 넣어줄지 결졍
print("Python", "Java",sep=",",end="?")
# end 한줄로 나오게 됨 문장의 끝부분을 물음표로 바꿔달라 
# 기본으로 end 줄바꿈으로 디폴트로 되어있었따.
print("무엇이 더 재밌을까요?")

import sys
print("Python","Java", file=sys.stdout)
#표준 출력으로 문장이 찍히는 거고
print("Python","Java", file=sys.stderr)
#표준 에러로 처리된다

scores = {"수학":0,"영어":50,"코딩":100}
for subject, score in scores.items():
    #print(subject,score)
    #숫자 정렬하고 싶다
    print(subject.ljust(8),str(score).rjust(4), sep=":")
    #왼쪽으로 정렬할건데 8개의 공간을 만들고 왼쪽 정렬

#은행 대기순번표
#001 002 003, ...
for num in range(1,21):
    print("대기번호 : "+str(num).zfill(3)) #0을 채우는 것
    #3의 크기로 값을 정하고 값이 없는 공간은 0으로 채워라

answer = input("아무 값이나 입력하세요 : ")
#사용자 입력을 통해 입력을 받으면 무조건 문자열이다.
print(type(answer))
print("입력하신 값은 "+ answer + "입니다.")



# 다양한 출력포맷 - Chapter

# 빈 자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 10자리 공간을 확보
print("{0: >10}".format(500))

# 양수일 떈 + 표시, 음수일 땐 - 표시
print("{0: >+10}".format(500))
print("{0: >+10}".format(-500))

# 왼쪽 정렬하고, 빈칸으로 _로 채움
print("{0:_<+10}".format(500))

# 3자리마다 콤마를 찍어주기
print("{0:,}".format(10000000000))

# 3자리마다 콤마를 찍어주기, +- 부호도 붙이기
print("{0:+,}".format(10000000000))

# 3자리마다 콤마를 찍어주기, 부호도 붙이고, 자릿수도 확보하기
# 돈이 많으면 행복하니까 빈 자리는 ^로 채워주기
print("{0:^<+30,}".format(1000000000))

# 소수점 출력
print("{0:f}".format(5/3))

# 소수점 특정 자릿수까지만 표시 (소수점 3째 자리에서 반올림)
print("{0:.2f}".format(5/3))


# 파일 입출력 - Chapter

#처음에는 파일 이름 그다음에는 쓰기위한 목적
#utf8정의해주지 않으면 한글 정의 이상 쓴느 걸 추천
# w 쓰기 용도
score_file = open("score.txt","w", encoding="utf8")
print("수학 : 0",file=score_file)
print("영어 : 50",file=score_file)
score_file.close()

#a 뒤에 이어서 쓰기 append a
score_file = open("score.txt","a",encoding="utf8")
score_file.write("과학 : 80")
#줄바꿈 해줘야함
score_file.write("\n코딩 : 100")
score_file.close()

# r은 리드
score_file = open("score.txt","r", encoding="utf8")
# 모든 내용들을 불러온다. .read()
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()

#방법 2
score_file = open("score.txt","r", encoding="utf8")
while True:
    line = score_file.readline()
    if not line:
        break
    print(line)
score_file.close()

#방법 3
score_file = open("score.txt","r", encoding="utf8")
lines = score_file.readlines() #list 형태로 저장
for line in lines:
    print(line, end="")
score_file.close()


# pickle - Chapter
# 프로그램 상에서 사용하는 데이터를 파일로 저장
import pickle
profile_file = open("profile.pickle","wb")#b 바이널 피클 쓰려면 b써야함 인코딩은 따로 필요없음
profile = {"이름":"박명수","나이":30,"취미":["축구","골프","코딩"]}
print(profile)
pickle.dump(profile,profile_file) #profile에 있는 정보를 file에 저장
profile_file.close()

profile_file = open("profile.pickle","rb")
profile = pickle.load(profile_file) #file에 있는 정보를 profile에 불러오기
print(profile)
profile_file.close()


# with - Chapter
import pickle
with open("profile.pickle","rb") as profile_file:
    print(pickle.load(profile_file))
#따로 클로즈 필요없음 자동으로 해준다.

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())

 

자료 : https://www.youtube.com/watch?v=kWiCuklohdY&t=1574s

Comments