공부/Python

Python/file read, write, Pickle

Chelsey 2022. 2. 10. 16:56
728x90

파일은 열면 읽거나 쓰고 닫아줘야한다. 파일을 여는게 메모리에 적재가 되기 때문에 많이하면 메모리 부족 현상이 일어나기 때문에 사용하지 않을 경우 닫아줘야한다.

file Open

파일을 열때는 write, read 각 목적을 적어줘야 한다.

# write 목적
f=open("test.txt". "w") 

# read 목적
f=open("test.txt", "r")

file read

아래의 with as 구문 방식은 해당 close()가 자동으로 되서 따로 해줄 필요가 없다.

f=open("test.txt", "r")
context=f.read()
print(context)
f.close()

# with as 구문 방식
with open("test.txt", "r") as f:
	context=f.read()
    print(context)

file write

f=open("test.txt", "w")
f.write("add some text")
f.close()

# with as 구문 방식
with open("text.txt", "w") as f:
	f.write("add some text")

with open("test.txt", "w") as f:
	for i in range(3):
    	f.write("textttt")

read, readline(s)

read : 파일을 읽어서 string type으로 가져옴

readline : 파일을 읽어서 list type으로 가져옴

f=open("test.txt", "r")
text=f.read()
#hello
#hi
#hallo

# or
text=f.readlines()
#['hello\n', 'hi\n', 'hallo']

readline으로 read처럼 string type으로 읽는법

with open("test2.txt","r") as f:
	line=None
	while line!="":
		line=f.readline()
		print(s.strip("\n"))

Pickle Module

객체를 파일로 저장

(프로젝트를 할 때 피클모듈을 많이 썼던게 기억난다)

import pickle

data='consume ... '
data2='kim sify'

with open("data.p", "wb") as f:
	pickle.dump(data, f)
    pickle.dump(data2, f)
    
with open("data.p", "rb") as f:
	data=pickle.load(f)
    data2=pickle.load(f)
print(data, data2)
728x90