파일 다루기 (feat. Pickle)

이상해씨·2023년 4월 7일
0

AI 기초

목록 보기
12/15

파일

1) Text 파일 : 문자열, 메모장으로 열렸을 때, 표시가 제대로 됨. 파이썬 , html
2) Binary 파일 : 이진법, 엑셀, 워드, 메모장으로 열었을 때, 이상한 문자 , 어플리케이션에 종속되어 있다.

FILE I/O

open 사용

  • 접근모드 (r읽기,w쓰기,a추가)
    f= open("<파일명>","<접근모드>")
    f.close()

파일 읽기

  • 같은 디렉토리에 있어야 함
    f=open(".txt", "r")
    data = f.read()
    f.close()
    with open(".txt","r") as file:
    data=file.read()
    print(type(data),data)
  • 파일 전체를 리스트로 반환
    with open(".txt","r") as file:
    data=file.readlines()
    word= data.split(" ")
    line= data.split("\n")
    
    print(type(data),data)
  • 한 줄 씩 읽기
    with open(".txt","r") as file:
    i=0
    while Ture:
    	line =file.realine()
    	if not line:
    		break
    	print(str(i) +line.replace("\n",""))
    	i=i+1

파일 쓰기

  • w, encoding ="UTF8"
f= open(".txt",'w',encoding="utf8")
for i in range(1,11):
	data ="%d번재 줄\n" %i
    f.write(data)
f.close()
  • a, 추가모드
with open(".txt",'a',encoding="utf8") as f:
	for i in range(1,11):
		data ="%d번재 줄\n" %i
    	f.write(data)

pickle

(출처 : https://www.bbc.co.uk/food/recipes/cucumber_and_dill_fridge_43183)


- 하나의 객체 및 클래스를 파일로 저장 (영속화) - 필요할 때 불러와서 사용 - 모델링, 계산결과 저장에 활용
  • dump(data, file) : 데이터를 파일에 저장
    - wb : 저장
    • rb : 불러오기
  import pickle

  # 저장
  f =open("lst.pickle","wb")
  test=[1,2,3]
  pickle.dump(test,f) # test 를 f에 저장
  f.close()

  # 불러오기 
  f =open("lst.pickle", "rb")
  load_pickle =pickle.load(f)
  f.close()


참고

profile
공부에는 끝이 없다

0개의 댓글