[Python] 표준입출력, 다양한 출력 포맷, 파일 입출력, Pickle, with

1. 표준입출력


# 문자열 사이에 sep을 통해 문자 삽입
# end를 통해 한문장으로 이어보기
print("Python", "Java", sep = ",", end = "?")
print("무엇이 더 재밌을까요?")

>>>
Python,Java?무엇이 더 재밌을까요?

import sys
print("Python", "Java", file = sys.stdout) # 표준 출력으로 문장 찍힘
print("Python", "Java", file = sys.stderr) # 에러로 문장 찍힘

>>>
Python Java
Python Java

# 왼쪽 정렬 : ljust, 오른쪽 정렬 : rjust
scores = {"수학":0, "영어":50, "코딩":100}
for subject, score in scores.items():
    print(subject.ljust(8), str(score).rjust(4), sep=":")
    
>>>
수학      :   0
영어      :  50
코딩      : 100

# 은행 대기순번표 : 001, 002, 003, ...
for num in range(1, 21):
    print("대기번호 : " + str(num).zfill(3))
    
# 답을 입력하면 문자열로 출력됨
answer = input("아무 값이나 입력하세요 : ")
print(type(answer))

>>>
아무 값이나 입력하세요 : 2
<class 'str'>

2. 다양한 출력 포맷

# 빈 자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 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(10000000000000))
# 3자리마다 콤마를 찍어주기, +- 부호도 붙이기
print("{0:+,}".format(10000000000000))
print("{0:+,}".format(-10000000000000))
# 3자리마다 콤마를 찍어주기, +- 부호도 붙이기, 자릿수 확보하기, 빈자리는 ^ 로 채워주기
print("{0:^<+25,}".format(10000000000000))
# 소수점 출력
print("{0:f}".format(5/3))
# 소수점 특정 자릿수 까지만 표시(소수짐 셋째자리에서 반올림)
print("{0:.2f}".format(5/3))

>>>
       500
      +500
      -500
500_______
10,000,000,000,000
+10,000,000,000,000
-10,000,000,000,000
+10,000,000,000,000^^^^^^
1.666667
1.67

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("\n코딩 : 100")
score_file.close()

# 파일에 있는 내용 읽기
score_file = open("score.txt", "r", encoding="utf8")
print(score_file.read())
score_file.close()

>>>
수학 : 0
영어 : 50
과학 : 80
코딩 : 100

# 줄별로 읽기, 한 줄 읽고 커서는 다음 줄로 이동
score_file = open("score.txt", "r", encoding="utf8")
print(score_file.readline(), end="")
print(score_file.readline(), end="")
print(score_file.readline())
print(score_file.readline())
score_file.close()

>>>
수학 : 0
영어 : 50
과학 : 80

코딩 : 100

# 반복문으로 파일 내용 읽어오기
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()

4. Pickle

# pickle : 프로그램 상에서 사용하는 데이터를 파일로 저장하고 이를 전달할 수 있음
import pickle
# 바이너리를 정의해줘야 함 +b
profile_file = open("profile.pickle", "wb")
profile = {"이름":"박명수", "나이":30, "취미":["축구", "골프", "코딩"]}
print(profile)
pickle.dump(profile, profile_file) # profile에 있는 정보를 file에 저장
profile_file.close()

>>>
{'이름': '박명수', '나이': 30, '취미': ['축구', '골프', '코딩']}

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

>>>
{'이름': '박명수', '나이': 30, '취미': ['축구', '골프', '코딩']}

5. with

import pickle

# pickle 파일을 열어서 profile_file로 읽는다.
with open("profile.pickle", "rb") as profile_file:
    print(pickle.load(profile_file))
    
>>>
{'이름': '박명수', '나이': 30, '취미': ['축구', '골프', '코딩']}

# 파일에 내용 쓰기
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

좋은 웹페이지 즐겨찾기