Maron's DATA Log

[Python] 입출력 본문

Python

[Python] 입출력

maron2ee 2020. 11. 30. 22:31

# 표준 입력 

* input( ) : 한 줄의 문자열을 입력 받는 함수

* map( ) : 리스트의 모든 원소에 각각 특정한 함수를 적용할 때

 

e.x)  공백을 기준으로 구분된 데이터를 입력 받을 때

list(map(int, input( ).split( )))

 

e.x)  공백을 기준으로 구분된 데이터의 개수가 많지 않다면

a, b, c = map(int, input( ).split( ))

 

# 빠르게 입력

sys.stdin.readlin( )

rstrip( )     # 입력 후 엔터가 줄 바꿈 기호로 입력 -> 오른쪽 공백 제거

 

 

# 표준 출력

* print( ) : 각 변수를 ',' 이용, 띄어쓰기로 구분해 출력

기본적으로 출력 이후 줄 바꿈을 수행하기 때문에, 줄 바꿈을 원치 않는 경우 end 속성 이용

 

print("Python", "Java")

print("Python", "Java", sep=",")

print("Python", "Java", sep=",", end="?")     # 문장의 끝 부분을 ?로 바꿔 다음줄과 연결. end 안쓰면 줄바꿈 defaulat 값

print("무엇이 더 재밌을까요?")

 

import sys

print("Python", "Java", file=sys.stdout)     # stdout : 표준 출력

print("Python", "Java", file=sys.stderr)     # stderr : 표준 error

 

# f-string

: 문자열 앞에 'f' 를 붙어 사용

 

e.x)

answer = 7

print(f"정답은 {answer}입니다."

 

 

# 시험 성적

scores = {"수학" : 0, "영어" : 50, "코딩" : 100}

for subject, score in scores.items( ):

   print(subject, score)

 

scores = {"수학" : 0, "영어" : 50, "코딩" : 100}

for subject, score in scores.items( ):

   print(subject.ljust(8), str(score).rjust(4), sep=":")    

# ljust(8) : 총 8칸의 공간을 확보한 상태에서 왼쪽 정렬 // rjust : 오른쪽 정렬

 

 

# 은행 대기순번표

for num in range(1, 21):

   print("대기번호 : " + str(num).zfill(3))     # zfill(3) : 3칸의 공간 확보 후 빈공간은 0으로 채움

 

 

answer = input("아무 값이나 입력하세요 : ")

print("입력하신 값은 " + answer + "입니다.")

 

print(type(answer))     # 사용자 입력을 통해서 값을 받게 되면 항상 문자열(str) 형태로 저장

 

 

 

 

 

# 다양한 출력포맷

# 빈 자리는 빈 공간으로 두고, 오른쪽 정렬, 총 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(500))

 

# 3자리 마다 "," 

print("{0:,}".format(1000000000000))

 

# 3자리 마다 ",", +- 부호

print("{0:+,}".format(1000000000000))

print("{0:+,}".format(-1000000000000))

 

# 3자리 마다 ",", +- 부호, 자리수 확보, 빈자리 ^로 

print("{0:^<+30,}". format(1000000000000))

 

# 소수점 출력

print("{0:f}".format(5.3))

 

# 소수점 특정 자리수 까지만 표시 - 소수점 3째 자리에서 반올림 (둘째자리까지만 표시)

print("{0:2f}".format(5.3))

 

 

# 파일입출력

score_file = open("score.txt", "w", encoding="utf8")     # w : 쓰기 목적

print("수학 : 0", file=score_file)

print("영어 : 50", file=score_file)

score_file.close( )

 

score_file = open("score.txt", "a", encoding="utf8")     # a : 덧붙여서 쓰기 (append)

score_file.write("과학 : 80")

score_file.write("\n코딩 : 100")     # .write 는 줄바꿈 자동으로 안되서 \n 으로 줄바꿈

score_file.close( )

 

score_file = open("score.txt", "r", encoding="utf8")     # r : 읽어오기

print(score_file.read( ))     # 전체 읽어오기

score_file.close( )

 

score_file = open("score.txt", "r", encoding="utf8")     

print(score_file.readline( ))     # 줄별로 읽기, 한 줄 읽고 커서는 다음 줄로 이동 // print 는 자동으로 줄 바꿈 되어서 격 줄로 출력

print(score_file.readline( ), end="")     # end="" 붙이면, 자동으로 줄 바꿈 안되서 다음 줄에 바로 출력

print(score_file.readline( ))     

print(score_file.readline( ))   

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

profile_file = open("profile.pickle", "wb")     # pickle 쓰려면 항상 wb - b: binary 타입으로 정의, 따로 인코딩 설정해줄 필요 없음

profile = {"이름" : "A", "나이" : 20, "취미" : ["축구", "골프", "코딩"]}

print(profile)

pickle.dump(profile, profile_file)     # profile 에 있는 정보를 file 에 저장

profile_file.close( )

 

import pickle

profile_file = open("profile.pickle", "rb") 

profile = pickle.load(profile_file)     # file 에 있는 정보를 profile 에 불러오기

print(profile)

profile_file.close( ) 

 

 

# With

: 따로 .close( ) 할 필요 없이 with 문 탈출하면 자동으로 종료

 

import pickle

with open("profile.pickle", "rb") as profile_file:

   print(pickle.load(profile_file))

 

with open("stduy.txt", "w", encoding="utf8") as study_file:     # 파일 쓰기

   study_file.write("파이썬을 열심히 공부하고 있어요.")

 

with open("stduy.txt", "r", encoding="utf8") as study_file:     # 파일 읽기

 

   print(study_file.read( )) 

Comments