본문 바로가기

Backend/Python

입출력

sep (값사이에 문자넣기) end (한줄에 여러개의 값 출력)

print("Python", "Java", sep=" , ", end=" ? ") # Python , Java ? + 줄안바뀜

ljust , rjust (왼쪽정렬, 오른쪽 정렬)

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

zfill 

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

다양한 출력포맷

# 빈 자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 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(10000000000))
# 소수점 출력
print("{0:f}".format(5/3))
# 소수점 특정 자리수까지만 표시(소수점 3째 자리에서 반올림)
print("{0:.2f}".format(5/3))

파일입출력

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

score_file = open("score.txt", "a", encoding="utf8")  # append
score_file.write("과학 : 80")
score_file.write("\n코딩 : 100") # \n을 해줘야 줄바꿈
score_file.close()

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

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 : 텍스트 상태의 데이터가 아닌 파이썬 객체 자체를 바이너리 파일로 저장하는 것.

import pickle

# 파일 저장(pickle.dump(객체, 파일))
profile_file = open("profile_pickle", "wb")  # write binary
profile = {"이름": "박명수", "나이": 30, "취미": ["축구", "골프", "코딩"]}
print(profile)
pickle.dump(profile, profile_file)  # profile에 있는 정보를 file에 저장
profile_file.close()

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

with : close를 사용하지 않고 파일을 저장, 로드 할 수 있음 

# 파일 저장 
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())

퀴즈

# 매주 1회 작성해야하는 보고서
# 1주차부터 50주차까지의 보고서 파일 생성
# 파일명 : 1주차.txt, 2주차.txt ...

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

for i in range(1, 51):
    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업무요약 : ")

 

'Backend > Python' 카테고리의 다른 글

예외처리  (0) 2022.02.06
클래스  (0) 2022.02.05
함수  (0) 2022.02.01
제어문  (0) 2022.02.01
자료구조  (0) 2022.01.31