관리 메뉴

me made it !

[Python] read(), readline(), readlines()의 차이 본문

크래프톤 정글

[Python] read(), readline(), readlines()의 차이

yeoney 2024. 7. 19. 15:28
반응형

0. 개요

파이썬에서는 파일 형태로 저장된 데이터를 읽어오는 3가지 방버이 있다. 바로 read(), readline(), readlines()에 대하여 알아보자. 

 

 

1. 전개


1. read()

: 파일을 통째로 읽는다. 파일 내 텍스트를 하나의 문자열로 변환

# example.txt 파일을 읽고 내용을 출력합니다.
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
    
# 결과값
Hello, this is the first line.
This is the second line.
And this is the third line.

 

2. readline()

: 줄 단위로 그대로 읽어와 붙여서 출력한다.

# example.txt 파일에서 한 줄씩 읽어서 출력합니다.
with open("example.txt", "r") as file:
    line = file.readline()
    while line:
        print(line, end='')  # 이미 줄바꿈 문자가 포함되어 있으므로 end=''을 사용
        line = file.readline()
        
# 결과값
Hello, this is the first line.
This is the second line.
And this is the third line.

 

 

3. readlines()

: 줄 단위로 읽어 줄 단위를 요소로 하는 리스트를 만들어 준다 . 개행 연산자(\n)를 줄 단위 끝에 붙여 준다.

filename = 'test.txt'
f = open(filename, 'r')
lines = f.readlines()
print(lines)
print('-' * 10)

for line in lines:
    print(line)

// 결과

['Hi\n', 'My name is\n', 'Python.']
----------
Hi

My name is

Python.

 

 

+ readlines() 에서 각 줄 사이 빈 줄을 없앨 때는 line.strip()을 사용한다.

filename = 'test.txt'
f = open(filename, 'r')
lines = f.readlines()
print(lines)
print('-' * 10)

for line in lines:
    line = line.strip()
    print(line)

// 결과 

['Hi\n', 'My name is\n', 'Python.']
----------
Hi
My name is
Python.

 

 

 

2. 결론


  • 실제 코딩에서는 각 줄을 분석하여 처리하는 경우가 더 흔하기 때문에 readlines() 를 활용
  • 또한 텍스트의 양이 많을 때 불필요하게 전체를 다 반환하는 read() 보다는 줄마다 필요한 정보를 처리할 수 있는 readlines() 를 더 선호
반응형

'크래프톤 정글' 카테고리의 다른 글

[C언어] Go to 문  (0) 2024.07.20
[CS]컴퓨터가 음수를 표현하는 방법  (0) 2024.07.20
[Python] For else 구문이 뭐야?  (0) 2024.07.17
[알고리즘] DFS 와 BFS  (0) 2024.07.13
[Python] strip() 과 split() 의 차이  (1) 2024.07.12