Programming/Python

[Python] 파이썬 파일 읽기(Read)에 대해서 알아보자.

빙기때침식곡 2021. 7. 31. 15:30
반응형

이미지 출처 www.python.org

 

오늘은 파이썬 파일 읽기에 대해서 알아보도록 하겠다.

 

 

1. open() 함수

 - 파이썬에서 제공하는 빌트인 함수

 - 파일을 여는데 사용하는 함수

 - 파일모드

  ① 'r' : 읽기 모드

  ② 'w' : 쓰기 모드 (기존파일 삭제) 

  ③ 'a' : 추가 모드 (파일 생성 또는 추가)

open([ 경로 ], [ 파일모드 ])

 

 

 

예제1. 파일 읽기 (1)

 - 객체를 할당해서 사용하는 방법

f = open('./Songs/listen.txt', 'r')
content = f.read()

print(content)

f.close()            # 반드시 close 리소스 반환

Result

Listen to the song here in my heart 
A melody I start but can't complete 
Listen to the sound from deep within
It's only beginning to find release

 

 

예제2. 파일 읽기 (2)

 - with문을 사용하는 방법

 - close()를 따로 작성 안해도 됨

with open('./Songs/listen.txt', 'r') as f:
    c = f.read()
    print(c)         # 읽은 문자열 출력
    print()
    print(list(c))   # 개별 문자를 리스트로 저장
    print()
    print(iter(c))   # iterator

Result

Listen to the song here in my heart
A melody I start but can't complete
Listen to the sound from deep within
It's only beginning to find release

['L', 'i', 's', 't', 'e', 'n', ' ', 't', 'o', ' ', 't', 'h', 'e', ' ', 's', 'o', 'n', 'g', ' ', 'h', 'e', 'r', 'e', ' ', 'i', 'n', ' ', 'm', 'y', ' 
', 'h', 'e', 'a', 'r', 't', '\n', 'A', ' ', 'm', 'e', 'l', 'o', 'd', 'y', ' ', 'I', ' ', 's', 't', 'a', 'r', 't', ' ', 'b', 'u', 't', ' ', 'c', 'a', 'n', "'", 't', ' ', 'c', 'o', 'm', 'p', 'l', 'e', 't', 'e', '\n', 'L', 'i', 's', 't', 'e', 'n', ' ', 't', 'o', ' ', 't', 'h', 'e', ' ', 's', 'o', 'u', 'n', 'd', ' ', 'f', 'r', 'o', 'm', ' ', 'd', 'e', 'e', 'p', ' ', 'w', 'i', 't', 'h', 'i', 'n', '\n', 'I', 't', "'", 's', ' ', 'o', 'n', 'l', 'y', ' ', 'b', 'e', 'g', 'i', 'n', 'n', 'i', 'n', 'g', ' ', 't', 'o', ' ', 'f', 'i', 'n', 'd', ' ', 'r', 'e', 'l', 'e', 'a', 's', 'e']

<str_iterator object at 0x000001DD851E3FA0>

 

 

예제3. 파일 읽기 (3)

 - for문으로 문자 하나하나 출력 가능

with open('./Songs/listen.txt', 'r') as f:
    for c in f:
        print(c.strip()) #strip 양쪽 공백을 없애줌 줄을 맞춰줌

Result

Listen to the song here in my heart
A melody I start but can't complete
Listen to the sound from deep within
It's only beginning to find release

 

 

예제4. 파일 읽기 (4)

with open('./Songs/listen.txt', 'r') as f:
    content = f.read()
    print(">", content)
    content = f.read() # 내용 없음 앞에서 다 읽어와서 뒤에는 읽을게 없다
    print(">", content)

Result

> Listen to the song here in my heart
A melody I start but can't complete
Listen to the sound from deep within
It's only beginning to find release
>

 

 

예제5. 파일 읽기 (5)

with open('./Songs/listen.txt', 'r') as f:
    line = f.readline() # 한줄만 읽음

    while line:
        print(line, end='### ')
        line = f.readline()

Result

Listen to the song here in my heart
### A melody I start but can't complete
### Listen to the sound from deep within
### It's only beginning to find release###

 

 

예제6. 파일 읽기 (6)

 - readlines()를 사용하면 리스트에 한줄씩 문자열을 갖는다.

with open('./Songs/listen.txt', 'r') as f:
    contents = f.readlines()      # contents 타입은 리스트
    print(contents)
    for c in contents:
        print(c, end = ' ******* ')

Result

['Listen to the song here in my heart\n', "A melody I start but can't complete\n", 'Listen to the sound from deep within\n', "It's only beginning to find release"]
Listen to the song here in my heart
 ******* A melody I start but can't complete
 ******* Listen to the sound from deep within
 ******* It's only beginning to find release *******
반응형