끄적끄적 코딩
Published 2020. 9. 11. 04:47
[파이썬] 파일 입출력 Python

open 함수를 통해서 파일을 열어줍니다.
첫번째 파라미터에서 대상을 적어주고,
두번째 파라미터에서 사용 방식을 적어줍니다. (r = read, w = write, a  = append)
encoding을 utf8로 지정해주는 것은 한글이 깨질 수 있기 때문입니다.

test_file = open("test.txt", "w", encoding="utf8")
print("Hello,", file=test_file)
print("Python!", file=test_file)
test_file.close()

파일을 w로 실행시켜서 print로 내용을 입력해보았습니다.
w로 실행시킨 내용은 안에 내용이 있다면 덮어씌어지게 됩니다.

결과 내용은 아래의 내용을 가진 test.txt 파일이 생성되었습니다.
Hello,
Python!

test_file = open("test.txt", "a", encoding="utf8")
test_file.write("Nice to ")
test_file.write("Meet You")
test_file.close()

다음으로 a로 동일한 파일을 실행해서
이번에는 test_file.write로 내용을 입력해보았습니다.
a로 속성을 주었기 때문에 파일의 마지막 내용 뒷부분에 쓰여졌습니다.

Hello,
Python!
Nice to Meet You

파일을 읽는 방법

test_file = open("test.txt", "r", encoding="utf8")
print(test_file.read())
test_file.close()

r로 파일을 실행시켰습니다.
print(test_file.read())를 실행시켜서 해당 파일을 내용을 모두 출력했습니다.

test_file = open("test.txt", "r", encoding="utf8")
while True:
    line = test_file.readline()
    if not line:
        break
    print(line, end="")
test_file.close()
print()

readline이 한줄 씩 읽는것인데 while문을 통해서 전부 출력해보았습니다

test_file = open("test.txt", "r", encoding="utf8")
lines = test_file.readlines()
for line in lines:
    print(line, end="")
test_file.close()

내용을 lines에 넣은 후에 for문을 통해 출력한 방식입니다.

'Python' 카테고리의 다른 글

[파이썬] with  (0) 2020.09.15
[파이썬] pickle  (0) 2020.09.13
[파이썬] print 속성, 포맷  (0) 2020.09.11
[파이썬] 지역변수, 전역변수  (0) 2020.09.10
[파이썬] 함수  (0) 2020.09.10

검색 태그