TIL | 파이썬 file

박지우·2021년 4월 19일
0

TIL

목록 보기
5/7
post-thumbnail

파일객체를 사용할때는
파일을 열고(open) -> 쓰거나(write) 읽고(read) -> 닫는다(close)

file=open('hello.txt','w') 파일객체 = open(파일이름, 파일모드)
-> 파일을 사용하기위해 open 함수로 파일을 열어 줌
file.write('hello,world!') 파일객체.write('문자열')
-> 파일에 문자열을(파일에 들어갈 내용) 저장
r = file.read() 변수 = 파일객체.read()
print(r)
-> 파일에서 문자열 읽기
file.close()
-> 파일 객체를 닫아줌
프로젝트 폴더에 hello.txt 파일이 만들어지고 내용이 들어가있음


파일모드 : 'w'(쓰기모드),'r'(읽기모드)

자동으로 파일 객체 닫기

with open(파일이름,파일모드) as 파일객체:
코드

with open('hello.txt','r') as file:#파일에 대한 객체를 자동으로 닫아줌
    r = file.read()
    print(r)

문자열 여러 줄을 파일에 쓰기

반복문을 사용하여 파일 작성

개행문자(\n)를 지정해주어야 줄바꿈이 되니 주의

with open('hello.txt','w') as file:
    for i in range(3):
        file.write('Hello,world! \n'.format(i))

리스트의 문자열을 파일에 쓰기

파일객체.writelines(문자열리스트)

lines = ['안녕하세요.\n', '파이썬\n', '코딩 도장입니다.\n']
 with open('hello.txt', 'w') as file:    # hello.txt 파일을 쓰기 모드(w)로 열기
    file.writelines(lines)

파일내용을 리스트로 가져오기 (읽기)

변수 = 파일객체.readlines()

 with open('hello.txt', 'r') as file:    # hello.txt 파일을 읽기 모드(r)로 열기
    lines = file.readlines()#파일의 내용을 한줄씩
    print(lines)
    #결과 ['안녕하세요.\n', '파이썬\n', '코딩 도장입니다.\n']

객체를 파일에 저장하는 pickle 모듈

객체를 파일에 저장하는 과정을 피클링(pickling)이라고 하고, 파일에서 객체를 읽어오는 과정을 언피클링(unpickling)이라고 한다.

피클링(pickling)

피클링 = 파이썬 객체를 파일에 저장
피클링은 pickle 모듈의 dump 메서드를 사용.
파일모드를 'wb'로 지정해야함

import pickle

name = 'ttakku'
age = 100
address = '서울시 OO구 OO동'
scores = {'korean':'90','english':'95','math':'70'}

with open('ttakku.p','wb') as file:#wb 설명 참고
    pickle.dump(name,file)
    pickle.dump(age,file)
    pickle.dump(address,file)
    pickle.dump(scores,file)

pickel.dump 로 객체(값)을 저장할 때는 파일 모드를 'wb'로 지정해야함
'wb'에서 b 는 binary를 뜻하는데, 바이너리 파일은 컴퓨터가 처리하는 파일 형식이라 텍스트 편집기로 열면 사람이 알아보기 어려움

(vscode에서 열어 본 ttakku.p)

파이썬 파일을 pickle.py 로 저장할 경우 에러 생김

Traceback (most recent call last):
File "/Users/ttakku/python/pickle.py", line 1, in
import pickle
File "/Users/ttakku/python/pickle.py", line 9, in
pickle.dump(name,file)
AttributeError: partially initialized module 'pickle' has no attribute 'dump' (most likely due to a circular import)

언피클링(unpickling)

언피클링 = 파일에서 파이썬 객체를 읽어 옴
언피클링은 pickle 모듈의 load를 사용함.
언피클링시 반드시 파일 모드를 바이너리 읽기 보드 'rb'로 지정해야함
rb : 바이너리 읽기 모드

import pickle

with open('ttakku.p','rb') as file: #ttakku.p 파일을 바이너리 읽기 모드로 열기
    name = pickle.load(file)
    age = pickle.load(file)
    address = pickle.load(file)
    scores = pickle.load(file)
    print(name)
    print(age)
    print(address)
    print(scores)

#실행결과 
#ttakku
#100
#서울시 OO구 OO동
#{'korean': '90', 'english': '95', 'math': '70'}

ttakku.p 파일을 저장할 때 pickle.dump 를 각 name,age, address,scores 네 번 사용했기 때문에

마찬가지로 파일에서 객체(값)을 가져올 때도 pickle.load를 네번 사용해야함.(저장 순서대로 가져올 때도 같은 순서로 가져옴)

profile
Backend developer

0개의 댓글