[Python_basic]표준 입출력, 출력포맷, 파일 입출력, pickle, with

Ronie🌊·2021년 1월 8일
0

Python👨🏻‍💻

목록 보기
6/11
post-thumbnail

git 바로가기


표준 입출력
출력포맷
파일 입출력
pickle
with


표준 입출력

  • 기본적으로 프로그램이 외부에서 오는 입력과 내부에서 보내는 출력을 추상화 시킨것이다.
  • 입력
    • input()
      입력한 값을 evaluate한 결과를 반환한다.
      즉, prompt를 pass했는지 안했는지 evaluate를 해야하기 때문에 더 느리다.
    • sys.stdin.readlines(n)
      개행문자도 입력을 받을 수 있고, 입력크기에 제한을 줌으로써 읽어들일 문자 수를 정할 수 있다.
    • 차이
      input은 prompt message를 입력받아 처리하기 때문에 약간의 부하로 작용될 수 있다. 또 input은 입력받은 값의 개행문자를 삭제해서 리턴한다.
      반면에 sys.stdin.readlines(n)는 개행문자를 포함하기 때문에 strip()를 추가해야할 필요성이 있다.
import sys

a = sys.stdin.readline().strip()

print("Input :", a)
# 결과
1 2 3 4 5
Input : 1 2 3 4 5
  • 출력
    • stdout
      출력버퍼에 있는 것을 뜻한다.
import sys
f=open('t.txt','w')
stdout=sys.stdout # 표준출력 저장(백업 개념)
sys.stdout=f
  • stderr
    • 에러 발생시 콘솔에 에러 메시지를 띄울 때 사용하는 방법
import sys
print("WARNING: ", "?", file=sys.stderr)

출력포맷

  • 데이터를 출력할때 커맨드상에서 보기좋게 편집한다.
    글자칸을 지정해주고, 정렬이나 빈칸채움 등이 있다.

  • ljust, rjust
    보기좋게 자리를 만들어 준다고 생각하면 된다.

    • ljust(n)는 왼쪽부터 n자리를 만들어 그안에 출력값을 넣는다. 왼쪽 정렬
    • rjust(n)는 오른쪽부터 n자리를 만들어 그안에 출력값을 넣는다. 오른쪽 정렬
scores={"math":0,"english":50,"coding":100}
for subject, score in scores.items():
    #print(subject, score)
    print(subject.ljust(8), str(score).rjust(4), sep=":")

for num in range(1,11):
    print("waiting num : "+str(num).zfill(3))

answer = input("input : ")
print(type(answer))
print("the input data is {0}" .format(answer))
출력결과
math    :   0
english :  50
coding  : 100
waiting num : 001
waiting num : 002
waiting num : 003
waiting num : 004
waiting num : 005
waiting num : 006
waiting num : 007
waiting num : 008
waiting num : 009
waiting num : 010
# 빈 자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 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))
print("{0:+,}".format(-10000000000))
# 3자리 마다 콤마를 찍어주고, 부호붙이고, 자릿수 확보하기(빈자리는 ^로 채우기)
print("{0:^<+30,}".format(10000000000))
# 소수점 출력
print("{0:f}".format(5/3))
# 소수점 특정 자리수 까지만 표시
print("{0:.2f}".format(5/3))
출력결과
       500
      +500
      -500
+500______
+10,000,000,000
-10,000,000,000
+10,000,000,000^^^^^^^^^^^^^^^
1.666667
1.67

파일 입출력

  • 말그대로 python에서 파일을 읽어와서 출력하는 것 이다.
# w덮어쓰기
score_file = open("score.txt", "w", encoding="utf8")
print("수학 : 0", file=score_file)
print("영어 : 50", file=score_file)
score_file.close() 

# 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")

# 한번에 다 읽어오기
print(score_file.read()) 

# 줄별로 읽기, 한 줄 읽고 커서는 다음 줄로 이동
print(score_file.readline(), end="") 
print(score_file.readline())
print(score_file.readline())
print(score_file.readline())

# 줄 수를 모를경우, 반복문
while True:
    line = score_file.readline()
    if not line:
        break
    print(line)

# list형태로 저장해서 출력
lines = score_file.readlines()
for line in lines:
    print(line, end="")
score_file.close() 

pickle

  • 원하는 데이터를 자료형의 변경없이 파일로 저장하여 그대로 로드할 수 있다. (open('text.txt', 'w') 방식으로 데이터를 입력하면 string 자료형으로 저장된다.)
# 프로그램 상의 데이터를 파일형태로 저장하는 것
import pickle

profile_file = open("profile.pickle","wb") #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()
출력결과
{'이름': '박명수', '나이': 30, '취미': ['축구', '골프', '코딩']}
{'이름': '박명수', '나이': 30, '취미': ['축구', '골프', '코딩']}

with

  • 파일 입출력을 할 때 해당 파일을 위해 open과 close를 해줘야하는 상황에서 처리가 끝나면 자동적으로 close해주는 것
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())
출력결과
{'이름': '박명수', '나이': 30, '취미': ['축구', '골프', '코딩']}
파이썬을 열심히 공부하고 있어요

0개의 댓글