open: 파일을 열겠다. "w": 쓰겠다. "utf8": 한글)
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()
파일의 내용을 읽어오기
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()
import pickle
피클: 프로그램 상 데이터를 파일 형태에 저장 > 파일을 누군가에게 주면 피클을 이용해 데이터를 사용 가능
profile_file = open("profile.pickle", "wb") # "w:쓰기/b: 피클사용"
profile = {"이름": "박명수", "나이": 30, "취미": ["축구", "골프", "코딩"]}
print(profile)
pickle.dump(profile, profile_file) # 프로필에 있는 정보를 파일에 저장
profile_file.close()
파일에서 데이터를 가지고 옴
profile_file = open("profile.pickle", "rb") profile = pickle.load(profile_file) # 파일 내 데이터를 가져와서 데이터 형태 print(profile) profile_file.close()
with: 파일 열고 닫는 행위를 쉽게 함
with open("profile.pickle", "rb") as profile_file: print(pickle.load(profile_file))
pickle 없이 with만 사용해서 파일 내에 쓰고 읽기
1) 쓰기with open("study.txt", "w", encoding="utf8") as study_file: study_file.write("파이썬을 공부하고 있어요.")
2) 읽기
with open("study.txt", "r", encoding="utf8") as study_file: print(study_file.read())
Q) 당신의 회사는 매주 1회 작성해야 하는 보고서가 있습니다.
보고서는 항상 아래와 같은 형태로 출력되어야 합니다.
'-X 주차 주간보고-
부서:
이름:
업무 요약:'
1~50주차까지의 보고서 파일을 만드는 프로그램을 작서하시오.
나의 코딩
while True: report_file = open(str(i)"주차.txt", "w", encoding="utf8") if i == 50: break report_file.write("- {0}주차 주간보고-".format(i) "\n부서 :" "\n이름 :" "\n업무 요약 :") report_file.close()
결과: SyntaxError: invalid syntax
이유: i를 for문에 넣었어야 하는데 while로 진행해서 작동되지 않음.
조금 더 반복문에 대한 논리와 구조를 짜는 연습을 해야겠다..
정답
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업무요약 :")
설명: for문을 이용해서 i를 50까지 반복시킴
i를 string으로 만드러주고 file.write를 4번 사용해서 각각의 내용이 자료 안에 작성될 수 있도록 만듦