Backend/Python

[Python] File Handling

sangwonYoon 2023. 3. 8. 00:56

파이썬에서 파일을 다루는 방법에 관해서 알아보자.


with

자원을 획득하고, 사용한 뒤, 반납할 때 주로 사용한다.

with open('myFile.txt', 'r') as my_file:
	contents = my_file.read()
	print(contents)

with 블록을 나가면서 자동으로 자원을 반납하기 때문에 파일 처리 시 close() 함수를 사용하지 않아도 된다.

 

readlines 함수

파일을 한 줄씩 읽어 list 타입으로 반환한다.

with open('myFile.txt', 'r') as my_file:
	content_list = my_file.readlines()
	print(type(content_list))
	# 출력: list

 

readline 함수

실행할 때마다 한 줄씩 반환한다.

with open('myFile.txt', 'r') as my_file:
	while True:
		line = my_file.readline()
		if not line:
			break
		print(line)