[python] 3. 입출력

Bik_Kyun·2022년 2월 24일
0
post-thumbnail

코테에서 결과를 출력할때 포맷도 중요하므로 복습했다.

1. stdin/stdout/stderr


1. stdin

  • input()
answer = input("아무 값이나 입력하세요 : ")
print("입력하신 값은 " + str(answer) + "입니다.")

이때 input()으로 입력 받은 값은 문자열이다.

2. stdout

  • sep= : 문자열 사이에 문자열 추가, 공백일 경우 띄어쓰기 효과.
print("Python", "Java", "JavaScript", sep=" vs ")

  • end= : 문자열 끝에 문자열 추가, 줄바꿈이 적용되지 않는다. 옵션을 함께 사용할 수 있다.
print("Python", "Java", "JavaScript", sep=" vs ", end="? ")
print("무엇이 더 재밌을까요?")

  • 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() : ()안의 숫자만큼 공간 확보후 빈칸을 '0'으로 채운다.
for num in range(1,5):
    print("대기번호 : " + str(num).zfill(3))


3. stderr
stdout과 유사하나 예외 및 오류 메시지를 출력할 때 사용. 예외처리시 많이 사용함.

import sys
print("Python", "Java", file=sys.stderr)


결과는 stdout과 같이 나오나 시스템상으론 다르다.

2. Output format

- {a:c>b}
b만큼 공간 확보후 a에 format값 대입 후 오른쪽 정렬.
빈 칸은 c로 채움(공백 사용 가능)

# 빈자리는 ?로, 오른쪽 정렬, 총 10자리 공간 확보
print("{0:?>10}".format(500))

# 양수일땐 +표시, 음수일땐 -표시
print("{0:?>+10}".format(500))
print("{0:?>+10}".format(-100))

- {a:c<b}
b만큼 공간 확보후 a에 format값 대입 후 왼쪽 정렬.
빈 칸은 c로 채움(공백 사용 가능)

# 빈자리는 ?로, 왼쪽 정렬, 총 10자리 공간 확보
print("{0:?<10}".format(500))

# 양수일땐 +표시, 음수일땐 -표시
print("{0:?<+10}".format(500))
print("{0:?<+10}".format(-100))


- {a:,}
숫자 3자리마다 ',' 찍음. 자릿수 표현.

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


- {a:f}
소수점을 표시할 때(f는 float를 의미)
f앞에 .숫자를 붙여서 소수 몇 번째 자리까지 보여줄지 표시.

# 소숫점 출력
print("{0:f}".format(5/3))

# 소숫점 두째 자리까지 표시(소숫점 셋째 자리에서 반올림)
print("{0:.2f}".format(5/3))

3. File Input/Output

open()

파일을 찾아서 연다. 파일이 없다면 파일을 생성한다.
연 파일은 무조건 close()를 사용하여 닫아주어야 한다.

- 쓰기

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


score라는 파일이 없기때문에 파일을 생성하고 print문의 내용을 파일에 쓴다.
만약 이미 score라는 파일이 있고 그 파일을 열었다면 그 파일의 내용을 덮어쓴다.

score_file = open("score.txt", "a", encoding="utf8") # 'a' = 이어쓰기(append)
score_file.write("과학 : 80")
score_file.write("\n코딩 : 100")
score_file.write("과학 : 80")
score_file.write("\n코딩 : 100")
score_file.close()


기존의 score파일에 이어쓴다. write문을 두 번 이어쓴 결과를 확인 할 수 있다.

- 읽기

# 모두 불러와서 읽기
score_file = open("score.txt", "r", encoding="utf8")
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()


print문을 4번만 실행했으므로 마지막 줄은 짤려 나오지 않은 것을 확인할 수 있다.

#한 줄씩 읽는데 파일이 몇줄인지 모를 경우 while문 사용
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() # 리스트 형태로 저장
for line in lines:
    print(line, end="")
score_file.close()

4. Pickle

pickle 라이브러리를 사용하면 파일에 문서를 binary 형태로 저장하고 그 문서를 불러온다.
파일 형태로 저장하기 때문에 사용자간 공유가 편해진다.

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


위의 내용이 profile.pickle 파일에 저장되었다.

이 저장된 내용을 profile 변수로 불러 오려면

profile_file = open("profile.pickle", "rb") #rb = read binary
profile = pickle.load(profile_file) # file에 있는 정보를 profile에 불러옴
print(profile)
profile_file.close()

5. With

앞에서 우리는 open()으로 파일을 열었을때 무조건 close()를 사용하여 파일을 닫아주어야 했다.
하지만 with 블럭을 사용하면 더 간단히 파일을 입출력할 수 있다.

import pickle

with open("profile.pickle", "rb") as profile_file:
    print(pickle.load(profile_file))
#열었던 파일을 close() 할 필요없이 with문이 종료되면 자동으로 파일을 닫아줌

#쓰기
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())

profile
비진

0개의 댓글