Python - Text 파일 읽고 쓰는 방법 (read, write, append)

파이썬에서 Text file을 읽고 쓰는 방법을 소개합니다. 파이썬도 C, Java 등 다른 언어에서 파일을 읽고 쓰는 것과 비슷한 방식으로 처리할 수 있습니다. 예제와 함께 알아보겠습니다.

1. 파일 Oepn, Close

파일을 읽거나 쓰려면 먼저 파일을 열어야 합니다.

open("File name", "Access mode")처럼 파일 이름과 Access mode를 인자로 전달해야 합니다.

file = open("TextFile.txt", "w");

경로 없이 파일 이름만 적으면 실행 파일과 동일한 경로에 있는 TextFile.txt 파일을 엽니다. 만약 파일이 존재하지 않으면 파일을 생성해줍니다.

다음과 같이 절대 경로를 전달하면 그 경로에 /home/js/test/ 디렉토리 아래에 파일이 생성됩니다.

file = open("/home/js/test/TextFile.txt", "w")

파일을 모두 사용했으면 다음과 같이 close()를 호출해야 합니다.

file.close()

2. Access mode

Access mode는 아래와 같은 것들이 있습니다.

Access mode Description
'r' Read only
'r+' Read and write. 파일이 없으면 에러 발생
'w' Write only. 파일이 없으면 파일 생성
'w+' Write and Read
'a' Append only
'a+' Append and read

3. 파일 읽기 (read)

/home/js/test/TextFile.txt 파일에 저장되어 있는 내용은 다음과 같습니다.

hello
python
world

3.1 readlines()

readlines()는 Line 단위로 텍스트를 읽고 List로 리턴해 줍니다.

아래 예제는 TextFile.txt의 모든 문자열을 읽고 출력하는 코드입니다.

file = open("/home/js/test/TextFile.txt", "r")
strings = file.readlines()
print(strings)
file.close()

Output:

['hello\n', 'python\n', 'world']

\n도 문자열에 포함되어 리턴됩니다.

마지막은 개행(new line)이 없기 때문에 \n가 포함되지 않았습니다.

3.2 readline()

readline()는 파일에서 1줄을 읽고 그 결과를 리턴해줍니다.

다음과 같이 while을 이용하면 모든 라인을 읽고 출력할 수 있습니다.

file = open("/home/js/test/TextFile.txt", "r")
while True:
    line = file.readline()
    if not line:
        break
    print(line)

file.close()

Output:

hello

python

world

print()에 전달되는 문자열에 \n가 포함되어 있기 때문에 개행(new line)이 출력되었습니다.

만약 \n을 제거하고 싶다면 strip()을 사용하면 됩니다.

file = open("/home/js/test/TextFile.txt", "r")
while True:
    line = file.readline()
    if not line:
        break
    print(line.strip())

file.close()

Output:

hello
python
world

strip() 함수에 대한 자세한 내용은 "Python - String strip(), rstrip(), lstrip()"를 참고해주세요.

print()와 개행(new line) 문자 관련하여 "Python - print() 줄바꿈 없이 출력"를 참고하실 수 있습니다.

3.3 read()

read()는 파일의 모든 텍스트를 1개의 String으로 만들어 리턴합니다.

file = open("/home/js/test/TextFile.txt", "r")
data = file.read()
print(data)
file.close()

\n도 모두 포함되기 때문에 출력하면 다음과 같이 출력됩니다.

Output:

hello
python
world

4. with로 파일 읽기

파일을 열 때 with를 사용하면 close()를 따로 호출하지 않아도 됩니다. with block이 종료될 때 스스로 close()를 호출해주기 때문입니다.

다음과 같이 with와 함께 사용할 수 있습니다.

with open("/home/js/test/TextFile.txt", "r") as file:
    strings = file.readlines()
    print(strings)

with에 대한 자세한 내용은 "Python - with로 파일 열고 닫기"를 참고해주세요.

5. 파일 쓰기 (write)

write()는 인자로 전달된 문자열을 파일에 씁니다.

with open("/home/js/test/TextFile.txt", "w") as file:
    file.write("Hello~ \n")
    file.write("World!")

Output:

Hello~
World!

Access mode "w"로 파일을 열면 파일 처음 위치에서 쓰게 됩니다.

즉, 기존 파일에 저장된 텍스트는 지워지고 새로 추가된 텍스트만 저장이 됩니다.

5.1 writelines()

writelines()는 List의 모든 텍스트를 파일에 저장합니다.

str_list = ["hello\n", "python\n", "world"]
with open("/home/js/test/TextFile.txt", "w") as file:
    file.writelines(str_list)

Output:

hello
python
world

5.2 Access mode: append

Access mode "a"는 append라는 의미로 파일을 쓸 때 마지막에 텍스트를 추가합니다.

예를 들어, 현재 TextFile.txt 파일의 내용이 아래와 같을 때,

Hello~
World!

다음 코드를 실행해보면 파일 마지막에 텍스트가 추가됩니다.

with open("/home/js/test/TextFile.txt", "a") as file:
    file.write("Hello~ \n")
    file.write("World!")
    file.close()

Output:

Hello~
World!Hello~
World!
Loading script...

Related Posts

codechachaCopyright ©2019 codechacha