본문 바로가기
Python

[Python] Text File : read and write

by ds31x 2023. 7. 4.

쓰기

open으로 얻은 file object의 메서드 write 또는 print 함수를 통해 쓰기를 수행함.

 

당연히 해당 file object는 wt or w 등과 같이 Text file로 쓰기 (or a or x)등으로 열려야 함.

2023.07.04 - [Python] - [Python] file : open and close

 

[Python] file : open and close

Python 에서 file을 처리하기 위해선 다른 프로그래밍 언어와 마찬가지로 file에 대한 접근이 가능한 object를 얻어와야함. 이같은 object는 file handler, file descriptor 등의 여러 이름으로 불리며, 이를 얻

ds31x.tistory.com


print() 함수

print 함수의 경우, standard output (stdout, 일반적으로 terminal)로 출력을 하는 것이 기본동작이나,

  • file parameter로 쓰고자 하는 file object를
  • keyward argument로 할당해 준 경우 파일에 출력이 이루어짐.

 

sep=' '라던지 end=\n' 등의 parameter들은 stdout에 출력할 때와 같으므로,

특별히 지정하지 않는 한, argument들을 사이에 space가 추가되고 newline이 붙어서 출력이 이루어짐.

print()
한 line을 출력하는 것을 기본 동작으로 하고 있음을 명심할 것.

다음 예제로 사용 방법을 확인하자.

with open('test0.txt','w') as fout:
    print('Test! This is a single line.',file=fout)

write() 메서드

write()메서드는 text mode에서 파일에 쓴 character(글자)의 수를 반환함.

txt = '''First line of text
Second line of text
Third line of text'''

with open('test1.txt','w') as fout:
    cnt = fout.write(txt)
    print(f'write : {cnt} characters.')
  • 주의할 것은 write 메서드는 맨 뒤에 newline을 추가하지 않음.
  • 있는 그대로 argument로 받은 string을 file에 씀.
  • 위의 예의 경우, multi-line string이므로 1,2번째 행들의 맨 끝에는 newline이 있음.

참고로 binary file의 경우에는 write
파일에 쓴 byte 수를 반환함.

 

만약 파일에 써야할 text가 매우 큰 경우에는 이를 다음과 같이 chunk로 나누어 처리하는게 일반적임.

txt = '''First line of text
Second line of text
Third line of text'''

with open('test2.txt','w') as fout:
    chunk = 10
    offset = 0
    max_size = len(txt)
    while offset <= max_size:
        print(f'num of character written : {fout.write(txt[offset:offset+chunk])}')
        offset += chunk

읽기

open으로 얻은 file object가 제공하는 다음의 메서드들을 통해 읽기를 처리함.

  • read : 통으로 한 번에 읽어들이거나 정해진 글자수(argument로 지정)만큼 읽어들이고, 읽어들인 문자열을 반환.
  • readline : 한 line을 읽어들이고 해당 line에 해당하는 문자열을 반환.
    • 읽어들인 line에 newline으로 끝날 경우, 반환된 문자열도 newline을 끝에 가지고 있음.
  • readlines : 한번에 file을 여러 라인들을 읽어들여 각 line을 item으로 가지는 list를 반환.

read

read()메소드는 arugment 없을 경우, 파일 전체를 읽어들이고, int로 argument를 줄 경우 해당 숫자의 글자를 읽어들임.

  • EOF(End of File)에 도달하여 더 이상 읽을 문자가 없을 경우, 빈문자열을 반환함.

다음 예를 참고.

txt = str()
with open('test2.txt', 'rt') as fin:
    txt = fin.read()

print(txt)

위의 경우, 한번에 전체 파일을 읽어들이기 때문에 매우 큰 사이즈의 파일을 읽을 때는 아래와 같이 나누어서 읽어들이는게 일반적임.

txt = str()
with open('test2.txt', 'rt') as fin:
    chunk = 10
    while buf := fin.read(chunk):
        txt += buf
print(txt)

readline

한 line씩읽어들임.

  • EOF(End of File)에 도달하여 더 이상 읽을 문자가 없을 경우, empty string(빈문자열)을 반환함.
txt = str()
with open('relativity', 'rt') as fin:
    while line := fin.readline():
        txt += line        
print(txt)

readlines

각 line을 item으로 가지는 list를 반환.

lines = None
with open('relativity', 'rt') as fin:
    lines = fin.readlines()

print(len(lines), 'lines read')
for line in lines:
    print(line, end='')
print('')

print('--------------')
tmp = ''.join(lines)
print(tmp)

file object 자체가 iterator임.

open으로 반환되는 file에 대한 객체는 _io.TextIOWrapper자체가 iterator임.

때문에 다음과 같이 for문으로 각 line별로 읽어들이는 게 가능함.

txt = str()
with open('relativity', 'rt') as fin:
        for l in fin:
            txt += l
print(txt)

binary file의 읽기 쓰기는 거의 비슷함.

다음 URL참고.

2023.07.04 - [Python] - [Python] binary file : write and read

 

[Python] binary file : write and read

txt file과 거의 비슷하나, 다음의 차이를 보임. 파일 내용을 담는데 사용하는 class가 str을 주로 쓰는 txt file의 경우와 달리 bytes와 bytearray를 사용한다. bytes는 immutable이고, bytearray는 mutable인 점을 기

ds31x.tistory.com

 

728x90