file = open('hello.txt', 'w') # hello.txt 파일을 쓰기 모드(w)로 열기. 파일 객체 반환
file.write('Hello, world!') # 파일에 문자열 저장
file.close() # 파일 객체 닫기
변수 = 파일객체.read()
file = open('hello.txt', 'r') # hello.txt 파일을 읽기 모드(r)로 열기. 파일 객체 반환
s = file.read() # 파일에서 문자열 읽기
print(s) # Hello, world!
file.close() # 파일 객체 닫기
에서 close()로 닫고하는게 힘들었는데 이번 문법을 통해서 자동으로 파일객체를 닫을수 있다!
with open(파일이름,파일모드)as 파일객체:
코드
with open('hello.txt','r')as file:
# hello.txt 파일을 읽기모드로 열기
s = file.read()
# 파일에서 문자열 읽기
print(s)
실행
hello, world!
with open('hello.txt', 'w') as file:
# hello.txt 파일을 쓰기 모드(w)로 열기
for i in range(3):
file.write('Hello, world! {0}\n'.format(i))
주의사항
1. 파일에 문자열을 저장할때는 무조건 \n 개행 문자를 넣어야지 나누어져서 문자가 출력 된다.
변수 = 파일객체.writelines(문자열 리스트)
코드
line=['안녕하세요'\n,'파이썬'\n,'코딩 도장입니다\n']
with open('hello.txt','r')as file:
lines =file.readlines()
print(lines)
실행결과
안녕하세요
파이썬
코딩도장 입니다.
변수 = 파일객체.readlines()
with open('hello.txt', 'r') as file: # hello.txt 파일을 읽기 모드(r)로 열기
lines = file.readlines()
print(lines)
실행결과
['안녕하세요.\n','파이썬\n','코딩도장'\n]
변수 = 파일객체.readline()
with open('hello.txt', 'r') as file: # hello.txt 파일을 읽기 모드(r)로 열기
line = None # 변수 line을 None으로 초기화
while line != '': # 빈문자열이 아닐떄 반복!
line = file.readline()
print(line.strip('\n')) # 파일에서 읽어온 문자열에서 \n 삭제하여 출력
readline으로 파일을 읽을때 while 반복문을 활용해야한다.
그 이유가 파일에 문자열이 몇줄이나 있는지 모르기때문이다!
None으로 초기화 안하면 while line ! =' '코드 자체가 거짓이 되기 때문에 None으로
초기화 해야한다.
with open('hello.txt', 'r') as file:
# hello.txt 파일을 읽기 모드(r)로 열기
for line in file:
# for에 파일 객체를 지정하면 파일의 내용을 한 줄씩 읽어서 변수에 저장
print(line.strip('\n'))
# 파일에서 읽어온 문자열에서 \n 삭제하여 출력
파이썬 객체를 파일에 저장하는과정을 피클링
파일에서 객체를 읽어오은 과정을 언피클링
import pickle
name = 'james'
age = 17
address = '서울시 서초구 반포동'
scores = {'korean': 90, 'english': 95, 'mathematics': 85, 'science': 82}
with open('james.p', 'wb') as file:
# james.p 파일을 바이너리 쓰기 모드(wb)로 열기
pickle.dump(name, file)
pickle.dump(age, file)
pickle.dump(address, file)
pickle.dump(scores, file)
소스코드 실행시 .py파일이 있는 폴더에 james.p파일이 생성
pockle.dump 객체를 저장할때 open('james.p', 'wb')와 같이 파일모드를 'wb'로 지정.
b는 바이너리를 뜻하고 컴퓨터가 처리하는 파일형식임.
파일에서 파이썬 객체를 읽어오는 언피클링 해보겠다.
언피클링 pickle 모듈의 load 사용
반드시 바이너리 읽기모드 'rb'로 지정
import pickle
with open('james.p', 'rb') as file:
# james.p 파일을 바이너리 읽기 모드(rb)로 열기
name = pickle.load(file)
age = pickle.load(file)
address = pickle.load(file)
scores = pickle.load(file)
print(name)
print(age)
print(address)
print(scores)
실행결과
james
17
서울시 서초구 반포동
{'korean': 90, 'english': 95, 'mathematics': 85, 'science': 82}