ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 파이썬 Day5
    파이썬 2021. 7. 17. 22:16
    728x90

    파이썬 기초 5

    표준 입출력


    print("Python" , "Java", "Javascript", sep=" vs ") #Python vs Java vs Javascript
    print("Python" , "Java", sep = ",", end="?")  #end="?"로인해 Python,Java?무엇이 더 재밌을까요? 출력
    print("무엇이 더 재밌을까요?")           
    
    import sys
    print("Python", "Java", file=sys.stdout) #표준 출력으로 문장이 찍힘
    print("Python", "Java", file=sys.stderr) #표준 에러로 처리, 프로그램 확인후 처리해줘야 함(따로)
    
    
    #시험성적
    scores = {"수학":0, "영어":50, "코딩":100}
    for subject, score in scores.items():
        # print(subject, score)   #일반출력
        print(subject.ljust(8), str(score).rjust(4))   #왼쪽끝과 오른쪽끝에 맞혀져서 나옴
    
    #은행 대기순번표
    001, 002, 003, ...
    for num in range(1, 21):
        #print("대기번호 : " + str(num)) # 1 2 3,,,20
        print("대기번호 : " + str(num).zfill(3)) #공간으 3개확보하고 나머지는 0으로 채워준다.
    
    answer = input("아무 값이나 입력하세요: ")    #사용자 값을 입력받을때는 str 형태로 받음
    print(type(answer))                          #숫자를 입력하는 문자형을 입력하든 type은 str형태
    print("입력하신 값은 : " + answer + "입니다.")  
    

    다양한 출력 포맷


    # 빈 자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 10자리 공간을 확보
    print("{0: >10}".format(500))   #(7자리차지)500
    
    #양수일 때 +로 표시, 음수일 땐 -로 표시
    
    print("{0: >+10}".format(500))    #>+해주면 앞쪽에 부호가 붙어서 출력된다.
    print("{0: >+10}".format(-500))
    
    #왼쪽 정렬하고, 빈칸을 _로 채움
    print("{0:_<+10}".format(500)) #+500______출력
    
    #3자리마다 콤마를 찍어주기
    print("{0:,}".format(10000000000))   #10000000000
    print("{0:+,}".format(10000000000))  #+10000000000
    print("{0:+,}".format(-10000000000)) #-10000000000
    
    #3자리마다 콤마를 찍어주기, 부호도 붙이고, 자릿수 확보하기
    #돈이 많으면 기분이 좋으니까 빈자리는 ^로 채워주기
    print("{0:^<+30,}".format(10000000000000)) #+10,000,000,000,000^^^^^^^^^^^
    
    #소수점 출력
    print("{0:f}".format(5/3))
    #소수점 특정 자리수 까지만 표시
    print("{0:.2f}".format(5/3))  #소수 3째 자리에서 반올림(1.67)

    파일 입출력


    score_file = open("score.txt", "w", encoding="utf8")  #w는 쓰기위한 용도, utf8은 한글 오류 없도록
    print("수학 : 0", file = score_file)
    print("영어 : 50", file = score_file)
    score_file.close()   #스코아라는 텍스트 파일이 생김
    
    score_file = open("score.txt", "a", encoding="utf8") #a는 이어쓰기
    score_file.write("과학: 80")
    score_file.write("\n코딩: 100")
    score_file.close()
    
    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()
    
    //다른곳에서 파일은 얻어와 몇줄인지 모를때
    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") #encoding설정 X, wb = 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)
    print(profile)
    profile_file.close()

    with


    import pickle
    
    with open("profile.pickle", "rb") as profile_file: #//close 필요없음
        print(pickle.load(profile_file))
    
    ----------------------------------------------------
    #//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())

    QUIZ


    Quiz) 회사에서 매주 1회 작성해야 하는 보고서가 있다.
    보고서는 항상 아래와 같은 형태로 출력되어야 한다.

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

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

    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업무 요약: ")
    
    # 1주차.txt ~ 50주차.txt 파일이 생성,아래와 같이 출력
    # - (1~50) 주차 주간보고 -
    # 부서: 
    # 이름: 
    # 업무 요약: 

    '파이썬' 카테고리의 다른 글

    파이썬 class_예제문제  (0) 2021.07.18
    파이썬 기초6  (0) 2021.07.18
    파이썬 Day4  (0) 2021.07.17
    파이썬 Day3  (0) 2021.07.17
    파이썬 Day2  (0) 2021.07.17

    댓글

Designed by Tistory.