본문 바로가기

_Programming/Python

Basic.입출력

# 표준 입출력
print("Python", "Java", sep=",")
print("Python", "Java", "Javascript", sep=" vs ") # Python vs Java vs Javascript

print("Python", "Java", sep=" , ", end="?") # 뒷 줄이 이어서 출력됌.
print("무엇이 더 재밌을까요?") # Python , Java?무엇이 더 재밌을까요?

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

score = {"수학":0, "영어":50, "코딩":100}
for subject, score in score.items():  # items()로 하게 되면 key와 value를 쌍으로 튜플로 보내줌.
    print(subject, score)    
    
score = {"수학":0, "영어":50, "코딩":100}
for subject, score in score.items():  # items()로 하게 되면 key와 value를 쌍으로 튜플로 보내줌.    
    print(subject.ljust(8), str(score).rjust(4), sep=":") 
    # ljsut(숫자) 숫자만큼의 공간을 확보하고 왼쪽정렬.
    # rjsut(숫자) 숫자만큼의 공간을 확보하고 오른쪽 정렬
 
# 은행대기 순번표
# 001, 002, 003, ...
for num in range(1,21):
    print("대기번호 : " + str(num).zfill(3)) # zfill(숫자) : 숫자만큼 공간을 잡고 값이 없는 나머지 0을 채움


answer = input("아무 값이나 입력하세요 : ") # input : 사용자의 대답을 기다림.
print("입력하신 값은" + answer + "입니다.") 
print(type(answer)) # type = str(문자)
# 즉 input으로 대답 받은 값은 항상 문자열 형식으로 저장된다.


# 다양한 출력포맷
 # 빈 자리는 빈 공간으로 두고, 오른쪽 정렬을 하되, 총 10자리 공간을 확보
 # 10자리 공간을 확보하되 >오른쪽정렬을 하고 500을 출력하고 나머지는 ''빈칸으로 채움.
print("{0: >10}".format(500))  
 # 양수일 땐 +로 표시, 음수일 땐 -로 표시
print("{0: >+10}".format(500))
print("{0: >+10}".format(-500)) 
 # 10자리 공간을 확보하되 <왼쪽정렬 하고 500을 출력하고 나머지는 '-'언더바로 채움.
print("{0:_<10}".format(500)) 
 # 3자리마다 ','콤마를 찍어주기. +,- 부호도 붙이기
print("{0:,}".format(100000000000))
print("{0:+,}".format(+100000000000))
print("{0:+,}".format(-100000000000))
 # 3자리마다 콤마를 찍어주고, 부호도 붙이고, 자릿수 확보하기, 빈자리는 ^로 채우기
 # 30자리만큼 공간을 확보하고 3자리마다 ','콤마를 찍고 왼쪽 정렬을 하고 빈 자리는 ^로 채우기
 # 순서 빈칸을뭘로  ---> 정렬방식 ---> 부호 ---> 총자릿수 ---> 3자리마다 콤마
print("{0:^<+30,}".format(+10000000000000))
 # 소수점 출력
print("{0:f}".format(5/3))
 # 소수점을 특정자리까지만
print("{0:.2f}".format(5/3))


# 파일입출력 : 열었으면 꼭 닫아주기
 # "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())
score_file.close()
 
 # 한 줄씩 읽어 오기 : 한줄 읽고 커서가 다음 줄로 이동하여 대기 후 또 한 줄 읽어옴
 # end="" : 자동으로 줄바꿈 해주는 것을 안한것!
score_file = open("score.txt", "r", encoding="utf8")
print(score_file.readline(), end="") 
print(score_file.readline())
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()

 # list형태로 저장
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") # b : binary. 꼭 사용해야함.
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()


# with : close()가 필요 없이 with 문을 빠져나옴과 동시에 파일 빠져나옴.
 # profile.pickle에 작성한 문서 내용 가져오기
import pickle
with open("profile.pickle", "rb") as profile_file:
    print(pickle.load(profile_file))
 # study.txt파일에 내용 쓰기
with open("study.txt", "w", encoding="utf8") as study_file:
    study_file.write("파이썬을 열심히 공부하고 있어요")
 # study.txt파일 내용 가져오기
with open("study.txt", "r", encoding="utf8") as study_file:
    print(study_file.read())


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

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

# 1주차부터 50주차까지의 보고서 파일을 만드는 프로그램을 작성하시오.
# 조건 : 파일명은 '1주차.txt', '2주차.txt', ... 와 같이 만듭니다.

# mine_sol
for week in range(1,51):
     with open("{0}주차.txt".format(week), "w", encoding="utf8") as report_xfile:
         report_xfile.write("{0}주차 주간보고 ".format(week))
         report_xfile.write("부서 : ")
         report_xfile.write("이름 : ")
         report_xfile.write("업무 요약 : ")

# other_sol
for i in range(1,51):
    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업무요약 :")

 

 

 

 

출처: www.youtube.com/watch?v=kWiCuklohd

 

'_Programming > Python' 카테고리의 다른 글

Basic.예외처리  (0) 2020.09.14
Basic.클래스  (0) 2020.09.11
Basic.함수  (0) 2020.09.09
Basic.제어문  (0) 2020.09.08
Basic.자료구조  (0) 2020.09.07