Python

[파이썬] 파일 입출력(write, read, pickle, with)

뉴라코 2024. 11. 9. 11:00
파일 내용 입력

-print 활용 (줄바꿈 알아서 됨)

score_file=open("score.txt","w",encoding="utf8") 
#w는 쓰기 위함이라는 뜻, utf8정의 안하면 한글정보 오류생기는 경우 생김
print("수학:0",file=score_file)
print("영어:50",file=score_file)
score_file.close() #파일 닫아주는 것까지 해야함

1. 스코어 파일 변수를 열겠다 open("score.txt","w",encoding="utf8") 

-> score.txt 라는 파일명에, 쓸것이고, 인코딩하겠다.

2.  값을 쓸 거고 file은 처음 정의한 스코어 파일이다. print("값",file= score_file)

3.  값을 다 썼으니 스코어 파일을 닫아주겠다. score_file.close()

*근데 이때 "w"으로 설정한 경우 덮어쓰기임.

 

- .write를 이용한 경우(줄바꿈 안되므로 \n 해줘야함)

score_file=open("score.txt","a",encoding="utf8") 
#a는 append 이어쓰기 위함이라는 뜻
score_file.write("과학:80") #.write 는 줄바꿈 따로 없음(print와 차이점)
score_file.write("\n코딩:100")
score_file.close() #파일 닫아주는 것까지 해야함

1. "a"는 append이고 이어쓰기 하겠다는 뜻

2, 스코어파일에 쓰겠다. score_file.write("값")

3. 줄바꿈 안되므로 다음거는 score_file.write("\n값")

4. 값을 다 썼으니 파일 닫아주겠다는 건 print와 똑같음. 


파일 내용 불러오기

-read를 활용하기

score_file = open("score.txt","r",encoding="utf8")
print(score_file.read())
score_file.close()

-readline 를 활용하기( 한 줄씩 불러오고 싶을 때 )

score_file = open("score.txt","r",encoding="utf8")
print(score_file.readline()) #줄별로 읽기, 한 줄 읽고 커서 다음줄
# print(score_file.readline(),end="") #프린트는 알아서 줄바꿈 되므로 싫다면 ,end="" 추가
print(score_file.readline())
print(score_file.readline())
print(score_file.readline())
score_file.close()

 

-while과 if 활용하기 (내가 가지고 오고 싶은 파일이 몇 줄인지 모를 때)

#다른 사람의 파일이 몇 줄인지 모를 때(반복물 while 과 if 사용)
score_file = open("score.txt","r",encoding="utf8")
while True: #반복루프
    line = score_file.readline()
    if not line:
        break #라인이 없다면 바로 반복문 탈출
    print(line)
    # print(line,end="") #줄 한줄씩 띄어지는거 싫다면
score_file.close()

-list에 넣어서 for in 활용하기

score_file=open("score.txt","r",encoding="utf8")
lines= score_file.readlines() #list형태로 저장
for line in lines:
    print(line, end="")
score_file.close()

1. lines를 readlines로 변수 저장하고

2. lines에서 line에 값을 넘겨주는 for line in lines 적기

3. 문장 당 한 줄씩 띄워지는거 싫어서 print(line, end="")


 

pickle -사용하는 데이터를 파일 형태로 저장하고 불러오기 유용한 라이브러리 ★

-pickle로 저장하기(profile.pickle, pickle.dump)

import pickle
profile_file=open("profile.pickle","wb") #피클 사용시 바이너리 꼭!, 피클에서는 인코딩 따로 설정 안해도됨
profile = {"이름":"박명수","나이":30,"취미":["축구","골프","코딩"]} #딕셔너리형으로, 취미는 리스트 
print(profile)
pickle.dump(profile,profile_file) #profile에 있는 정보를 file에 저장
profile_file.close()

1. import pickle 해준 후 open("profile.pickle","wb")라는 것은 profile.pickle이라는 파일이름 만들고 저장하겠다.

2. profile이라는 변수에 값을 넣어주고 pickle.dump(profile,profile_file) 프로파일의 값을 파일에 저장해라.

 

-pickle에서 불러오기(pickle.load)

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

1. open("profile.pickle","rb") 읽기용으로 가지고 오겠다.

2. profile= pickle.load(profile_file) 파일에서 가지고 오겠다.


with (닫아줄 필요 없음. no closing) , pickle보다 간단함

-pickle을 사용할 때

import pickle

with open("profile.pickle","rb") as profile_file:
    print(pickle.load(profile_file))

1. pickle의 내용 불러올 때 with open(문서명,용도) as 파일명: 

- 이 뜻은 저 '문서'를 '파일명'에 저장하겠다. 

2. 바로 print(pickle.load(파일명))

 

-어디서 가져오는 것 없이 간단히 

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. with as 사용하니 첫 번째 문단 새로운 문서 만드는 것도 두 줄, 두 번째 문단 새로운 문서 읽는 것도 두줄.

 


파일 관련 문제

나의 문제 풀이

week=range(1,51)
report_file=open("{0}주차.txt".format(week),"w",encoding="utf8")
print("-{0}주차 주간보고-".format(week),file= report_file)
print("부서 : ",file= report_file)
print("이름 : ",file= report_file)
print("업무 요약 :",file= report_file)
report_file.close()

-> 패착 원인: range 쓰고 싶었는데 어떻게 넣는지 까먹음..ㅜ

 

강사님 문제 풀이

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. range로 하나씩 넣고 싶을 땐 for i in range가 자동으로 나오게!

2. 파일 오픈이 아니라 with open 사용해서 그냥 report_file.wirte사용! (클로징 안해도 되니까)

3. 파일명이 1주차, 2주차, 3주차 이런식으로 바뀌므로 with open( i +"주차.txt" ,....) 인데 i는 숫자니까 str(i)+"주차.txt"