Python 뿌시기

[Python 문법 5] - 표준입출력, 출력포맷, 파일 입출력, pickle, with

pjw250 2024. 9. 26. 23:02

### 표준 입출력

print('Python', 'Java',sep=',', end='?') # sep은 인수 사이마다 넣을 값
print('무엇이 더 재밌을까요?') # end를 통해 값을 넣고 다음 print를 같은 줄에 출력

import sys
print('Python', 'Java', file=sys.stdout) # 표준 std로 출력
print('Python', 'Java', file=sys.stderr) # err std로 출력 (추후 수정사항 채크 시 활용)

# 출력 시 좌/우 정렬
scores = {'수학':0,'영어':50,'과학':100}
for subject, score in scores.items():
    print(subject.ljust(8),str(score).rjust(4), sep=':')
    # ljust(n) : n 자릿 수 내에서 좌측 정렬
    # rjust(n) : n 자릿 수 내에서 우측 정렬
    # sep : 출력 값들 사이에 값 삽업

for num in range(1,21):
    print(str(num).zfill(3))
    # 001, 002, 003 ~ 으로 빈 공간은 0을 채우면서
    # 3자리로 숫자를 출력함.

# input 함수는 무조건 str로 변수 type이 저장된다.
answer1 = 10
answer2 = input('아무 값이나 입력하세요 : ')
print(type(answer1)) # 'int'로 출력
print(type(answer2)) # 'str'로 출력

### 다양한 출력 포맷


print('{0: >10}'.format(500))
print('{0: >+10}'.format(500))
print('{0: >+10}'.format(-500))
print('{0:_<+10}'.format(500))
print('{0:,}'.format(1000000))
print('{0:+,}'.format(1000000))
print('{0:+,}'.format(-1000000))
print('{0:^<+30,}'.format(-1000000))
print('{0:f}'.format(5/3))
print('{0:.2f}'.format(5/3))

### 파일 입/출력
score_file = open('score.txt', 'w', encoding='utf8') # 파일 생성 후 입력, 닫기 (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('과학:100') # write는 줄바꿈이 안됨
score_file.write('\n코딩:100') # \n 처리를 해줘야 함
score_file.close()

score_file = open('score.txt', 'r', encoding='utf8')
print(score_file.read()) # 파일을 전부 다 읽기 (read)
score_file.close()

score_file = open('score.txt', 'r', encoding='utf8')
print(score_file.readline(), end='') # readline 한줄 읽기
print(score_file.readline(), end='') # 한 줄 읽으면 enter 후
print(score_file.readline(), end='') # 다음 줄로 커서가 이동하기 때문에
print(score_file.readline(), end='') # 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 (작업 중 종료할 때 작업 중 사용한 리스트, 딕셔너리를 저장 후 나중에 불러오기)

# pickle로 파일에 변수 저장하기
import pickle
profile_file = open('profile.pickle', 'wb') # b 바이너리라는 뜻, w는 write
profile = {'이름':'박재완', '나이':35, '취미':['축구', '골프', '코딩']}
print(profile)
pickle.dump(profile, profile_file) # profile 에 있는 정보를 profile.pickle에 저장
profile_file.close()

import pickle
profile_file = open('profile.pickle', 'rb') # b 바이너리라는 뜻, r는 read
profile = pickle.load(profile_file) # file에 있는 정보를 pofile에 불러오기
print(profile)
profile_file.close()

### with (pickle과 파일을 간략하게 쓰고 읽기), file.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())

    '''당신의 회사에서는 매주 1회 작성해야하는 보고서가 있습니다.
보고서는 항상 아래와 같은 형태로 출력되어야 합니다.

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

1주차부터 5주차까지의 보고서 파일을 만드는 프로그램을 작성하시오.

조건 : 파일명은 '1주차.txt', '2주차.txt', ... 와 같이 만듭니다.'''
# 내가 작성한 코드
for num in range(1,6):
    report_file = open('{0}주차.txt'.format(num), 'w', encoding='utf8')
    report_file.write('- {0} 주차 주간보고 -'.format(num))
    report_file.write('\n부서 :')
    report_file.write('\n이름 :')
    report_file.write('\n업무 내용 :')    
    report_file.close()

# 정답 코드 (with 이용)
for num in range(1,6):
    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업무 요약 :')

 

* 출처 나도코딩 [파이썬 코딩 무료 강의 (기본편)]

파이썬 코딩 무료 강의 (기본편) - 6시간 뒤면 여러분도 개발자가 될 수 있어요 [나도코딩] (youtube.com)