Rylah's Study & Daily Life

[Python Basic] 08. 표준 입출력, 다양한 출력 포맷, 파일 입출력, pickle, With 본문

Study/Python Basic

[Python Basic] 08. 표준 입출력, 다양한 출력 포맷, 파일 입출력, pickle, With

Rylah 2022. 1. 19. 13:54
# 1. 표준 입출력
print("Python", "Java", sep=", ")
print("Python", "Java", "JavaScript", sep=" vs ")
print()
print("Python", "Java", sep=",")#, end="?")
print(" 무엇이 더 재밌을까요?")
print("Python", "Java", sep=",", end="?") # end 부분의 default = \n end 변경 가능
print(" 무엇이 더 재밌을까요?")

import sys
print("Python", "Java", file=sys.stdout) # stdout
print("Python", "Java", file=sys.stderr) # stderr (에러 처리)

print()

#시험 성적
scores = {"수학":0, "영어":50, "코딩":100}
for subject, score in scores.items():
    print(subject.ljust(8), str(score).rjust(4),sep=":")

# 은행 대기 순번표
# 001, 002, 003
for num in range(1,21):
    print("대기 번호 : " +str(num).zfill(3)) 


answer = input("아무 값이나 입력하세요 : ") # input은 항상 문자열로 저장된다.
print(type(answer))
print(f"입력 하신 값은 {answer}입니다.")

# 2. 다양한 출력 포맷
# 빈 자리는 빈 공간으로 두고 오른쪽 정렬을 하되, 총 10자리 공간을 확보
print("{0: >10}".format(500))
print("{0: >10}".format(-500))
# 양수 일 때는 +로 표시, 음수 일때는 -로 표시
print("{0: >+10}".format(500))
print("{0: >+10}".format(-500))
print("{0: >+10}".format(0))

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

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

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

# 소수점 출력
print("{0}".format(5/3))
# 소수 점 특정 자리수만큼 출력
print("{0:.2f}".format(5/3))
decimal = 5/3
print(f"{decimal:.5f}")

# 3. 파일 입출력

score_file = open("score.txt", "w", encoding="utf8")
print("수학 : 0",file=score_file)
print("영어 : 50",file=score_file)
score_file.close()

score_file = open("score.txt", "a", encoding="utf8")
score_file.write("과학 : 80\n")
score_file.write("코딩 : 100")
score_file.close()

score_file = open("score.txt", "r", encoding="utf8")
print(score_file.read())
score_file.close()
print()
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()
print()
print()
score_file = open("score.txt", "r", encoding="utf8")
while True:
    line = score_file.readline()
    if not line:
        break
    print(line,end="")
score_file.close()
print()
print()
score_file = open("score.txt", "r", encoding="utf8")
lines = score_file.readlines() #list 형태로 저장
for line in lines:
    print(line, end="")
score_file.close()

console
score.txt

# 4. pickle
import pickle
profile_file = open("profile.pickle", "wb") # Write, Binary
profile = {"이름":"박명수", "나이":30, "취미":["축구", "골프", "코딩"]}
print(profile)
pickle.dump(profile, profile_file) # profile에 있는 정보를 profile_file에 저장
profile_file.close()

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

console
pickle

# 5. With

import pickle

with open("profile.pickle", "rb") as profile_file:
    print(pickle.load(profile_file))
# with는 루프를 탈출하면서 자동으로 닫는다. 
# close를 해주지 않아도 된다.

# no use pickle 

with open("study.txt", "w", encoding="utf8") as study_file:
    study_file.write("Studying hard to Python and All PS")

with open("study.txt", "r", encoding="utf8") as study_file:
    print(study_file.read())

console
Study.txt

Quiz) 당신의 회사에서는 매주 1회 작성해야하는 보고서가 있습니다.
보고서는 항상 아래와 같은 형태로 출력되어야 합니다.

- X 주차 주간 보고 -
 부서 : 
 이름 : 
 업무 요약 : 

 1주차부터 50주차까지의 보고서 파일을 만드는 프로그램을 작성하시오.

 조건 : 파일명은 '1주차.txt', '2주차.txt', .... 와 같이 만듭니다.

 

# Quiz) 당신의 회사에서는 매주 1회 작성해야하는 보고서가 있습니다.
# 보고서는 항상 아래와 같은 형태로 출력되어야 합니다.

# - X 주차 주간 보고 -
#  부서 : 
#  이름 : 
#  업무 요약 : 

#  1주차부터 50주차까지의 보고서 파일을 만드는 프로그램을 작성하시오.

#  조건 : 파일명은 '1주차.txt', '2주차.txt', .... 와 같이 만듭니다.

for i in range(1,51):# 1 ~ 50
    with open(str(i) + "주차.txt","w",encoding="utf8") as report_file:
        report_file.write(" - {0} 주차 주간 보고 - ".format(i))
        report_file.write("\n 부서 : ")
        report_file.write("\n 이름 : ")
        report_file.write("\n 업무 요약 : ")