본문 바로가기
Python/PythonLibrary

open( ) / with~ as~ 문 /

by leehii 2022. 10. 7.

open()  >> quit() , close()

닫아주지 않으면 객체가 열려있어 메모리 점유

with~as~를 통해 자동으로 객체를 닫아줄 수 있음

 

# 경로에 \를 쓸 경우 \\로 두개를 쓰거나 앞에 r문자를 붙여줘야 함)
#Raw String :  r'~~\디렉토리~~' 
path = '경로'

 

 

# r : 읽기모드 / w : 쓰기모드 / a : 추가모드 (파일 마지막)

file = open(path='/파일명', 'w')
for i in range(1,11) :
	data = f'{i}번째 줄\n'
	file.write(data)
file.close()

 


file = open(path='/파일명', 'r')
# 1. read_line으로 읽어오기
line = file.readline()
print(line)
file.close()

# while 문으로 한줄씩 읽어오기
while True:
    line = file.readline()
    if not line: break
    print(line)
    
file.close()
# 2. readlines : 모든 줄을 읽어 각 줄을 list로 반환
lines = file.readlines()
for line in lines :
	print(line)
    
file.close()
# 3. read로 읽어오기

data = file.read()
print(data)
f.close()

 

 

# with open 사용 예시

# file에 글쓰기
with open(path+'파일명', 'w') as file :
	file.write('test_message')

# file json객체로 저장
import json
dict = {'key' : 'value'}
with open('파일명.json', 'w') as file :
	json.dump(dict, file)