파일 읽기

f = open('./test.txt', 'r')
contents = f.read()
print(contents)
f.close()

"""

출력문

abcdefgh
ijklmnop
qrstuvwx
yz

"""

open 메서드를 통해 파일과 연결되며, read 메서드로 파일 내 모든 데이터들을 읽어 들인다.

마지막으로 사용이 끝나면 반드시 close메서드로 리소스를 반환해줘야 한다.

with open('./test.txt', 'r') as f:
    c = f.read()
    print(iter(c))
    print(list(c))
    print(c)

"""

출력

<str_iterator object at 0x0000021837F7B348>
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\n', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', '\n', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', '\n', 'y', 'z']
abcdefgh
ijklmnop
qrstuvwx
yz

"""

매번 close 하기가 번거로우므로 위의 코드처럼 with 문을 써주면 자동으로 close 처리가 된다.

 

strip 메서드

with open('./test.txt', 'r') as f:
    for c in f:
        print(c)

"""

abcdefgh

ijklmnop

qrstuvwx

yz

"""

각 줄의 끝에 '\n'에 의해서 사이사이에 한 줄씩 띄어져 있다.

이를 해결하기 위해서 양쪽의 공백을 제거해주는 strip메서드를 사용한다.

with open('./test.txt', 'r') as f:
    for c in f:
        print(c.strip())
        
"""

abcdefgh
ijklmnop
qrstuvwx
yz

"""

readline 메서드

한 줄 단위로 읽으며, 파라미터로 숫자를 기입할 경우, 해당 숫자만큼의 문자를 읽어 들인다.

with open('./test.txt', 'r') as f:
    line = f.readline()
    while line:
        print(line, end='')
        line = f.readline()

"""
abcdefgh
ijklmnop
qrstuvwx
yz
"""

readlines 메서드

전체를 읽고 한 줄 단위로 리스트에 저장한다.

with open('./test.txt', 'r') as f:
    lines = f.readlines()
    print(lines)
    print()
    for line in lines:
        print(line, end='')
        
"""
['abcdefgh\n', 'ijklmnop\n', 'qrstuvwx\n', 'yz']

abcdefgh
ijklmnop
qrstuvwx
yz
"""

 

파일 쓰기

쓰기 모드('w') 또는 추가 모드('a')로 설정해주면 파일 쓰기를 할 수 있다.

from random import randint

with open('./result.txt', 'w') as f:
    for cnt in range(6):
        f.write(str(randint(50, 100)))
        f.write('\n')
        
        
"""
result.txt

54
64
91
96
67
76

"""

writelines

리스트를 파일로 저장

with open('./result.txt', 'w') as f:
    list = ['kim\n', 'park\n', 'lee\n']
    f.writelines(list)
    

"""
result.txt

kim
park
lee

"""

'Programming Language > Python' 카테고리의 다른 글

Python - 예외, 예외처리  (0) 2020.03.16
Python - 모듈, 패키지  (0) 2020.03.14
클래스(class)  (0) 2020.03.13
람다식  (0) 2020.03.13
*args, **kwargs  (0) 2020.03.13

+ Recent posts