본문 바로가기
Computer & Program/python

[python] File I/O

by TDRemon 2024. 2. 3.
반응형

안녕하세요. TDR입니다.

오늘은 python에서 File Input / Output을 어떻게 하는지 간략하게 살펴 보겠습니다.

File을 열 때 어떤 모드로 열지를 결정할 수 있습니다. 대표적인 형태로는 아래 4가지가 있습니다.

File open mode
r : 읽기 모드
w : 쓰기 모드
a : 수정 모드
x : 쓰기 모드. 배타적 생성으로 파일이 없으면 생성하고, 있으면 오류 발생 (FileExsitsError)

File 읽기

## 기본적인 형태 01
file = open('input.txt', 'r')	# input.txt 파일을 읽기모드(r)로 염
line = None
while line != '':
	line = file.readline()	# file에서 한줄씩 읽어 들임
file.close()	# 열었던 file은 닫아야 함


## 기본적인 형태 02
file = open('input.txt', 'r')
while True:
    line = file.readline()
    if not line:
    	break
file.close()	# 열었던 file은 닫아야 함


## with - as로 file을 열면 명시적으로 close를 할필요 없음
with open('input.txt', 'r') as file:
	list_object = file.readlines()	# list형태로 각 라인을 읽어 들임
    

# file.read()와 같이 파일 전체를 읽어 들일 수 있음

# file을 text 형태로 읽으려면 file mode 뒤에 t를 추가
with open('input.txt', 'rt') as file:
	pass

# file을 binary 형태로 읽으려면 file mode 뒤에 b를 추가
with open('input.txt', 'rb') as file:
	pass

File 쓰기

## 쓰기 기본적인 형태
with open('output.txt', 'w') as file:
	file.write('first line\n')
	file.write('second line\n')
# 입력 스트링 뒤에 '\n'을 안 넣으면 한줄로 출력이 됨


## list를 쓰기
with open('output.txt', 'a') as file:
	list_object = ['first line\n', 'second line\n']
	file.writeline(list_object)
    

# file.writeable()를 통해 해당 파일이 쓰기가 가능한지 확인 가능
# 쓰기가 가능하면 True 반환


## file mode별 차이
'w' : 파일을 쓰기 모드로 열고, 기존에 내용이 있으면 덮어 씌움
'a' : 파일을 쓰기 모드로 열고, 기존 내용에 추가해서 입력함
'x' : 파일이 없으면 생성하고 쓰기 모드로 열고, 파일이 있으면 FileExsitsError 발생

Pickle library

object를 file.write() binary mode로 쓸 수는 있지만 원하는 객체를 꺼내올 수는 없습니다.. 그래서 pickle과 같은 Library를 사용해야 합니다.

## pickle library를 써서 object(객체) 저장 / 읽기
import pickle

name = 'james'
age = 17
address = 'Seoul'
score = {'korean': 90, 'math': 100, 'english': 85}

# file에 object 저장
with open('input_bin.bin', 'wb') as file:
	# 피클링(pickling) : 객체를 파일에 저장
	pickle.dump(name, file)
	pickle.dump(age, file)
	pickle.dump(address, file)
	pickle.dump(score, file)
	
# file에서 object 읽기
with open('input_bin.bin', 'rb') as file:
	# 언피클링(unpickling) : 파일에서 객체를 불러옴
	name = pickle.load(file)	# james
	age = pickle.load(file)		# 17
	address = pickle.load(file)	# Seoul
	score = pickle.load(file)	# {'korean': 90, 'math': 100, 'english': 85}

pickle을 보면 마치 json을 다루는 것과 유사해 보입니다. 실제로 dump(), dumps(), load(), loads() 메소드를 제공하고 그 역할 또한 매우 유사합니다.

반응형

'Computer & Program > python' 카테고리의 다른 글

[python] reduce 함수  (0) 2024.02.15
[python] filter 함수  (0) 2024.02.14
[python] for 반복문  (0) 2024.02.02
[python] String - 02  (0) 2024.01.31
[python] String - 01  (0) 2024.01.30

댓글