파이썬 - 파일 입출력 및 삭제

jaybon·2022년 10월 26일
1

파이썬

목록 보기
6/20

파일 생성 및 입력

# open을 이용해서 파일을 생성하고 파일에디터를 호출한다.
file_editor = open(file="test.txt", mode="w", encoding="utf-8")

# write를 이용해서 내용을 입력한다.
file_editor.write("안녕하세요.")

# 파일에디터를 닫는다.
file_editor.close()

주의!

파일 에디터를 사용한 경우 꼭 닫아주어야한다.(close())

프로그램이 종료될 경우 에디터가 자동으로 닫히나 직접 닫아주는 것이 좋다.

에디터가 열려있을 경우 문제가 발생할 수 있다.

mode 종류

파일 수정

# open을 이용해서 파일을 생성하고 파일에디터를 호출한다.
file_editor = open(file="test.txt", mode="a", encoding="utf-8")

# write를 이용해서 내용을 입력한다.
file_editor.write("\n반갑습니다.")

# 파일에디터를 닫는다.
file_editor.close()

파일 읽기

read()

파일 내용을 하나의 문자열에 담는다.

# 파일을 읽기모드로 연다. 파일이 없으면 에러가 발생한다.
file_editor = open(file="test.txt", mode="r", encoding="utf-8")

# 파일을 읽는다.
text = file_editor.read()

# 파일에디터를 닫는다.
file_editor.close()

print(text)

# 안녕하세요.
# 반갑습니다.

readline()

파일의 내용을 한줄씩 가져온다.

# 파일을 읽기모드로 연다. 파일이 없으면 에러가 발생한다.
file_editor = open(file="test.txt", mode="r", encoding="utf-8")

# 파일에서 한줄씩 읽는다.
text = file_editor.readline()
text1 = file_editor.readline()

# 파일에디터를 닫는다.
file_editor.close()

print(text)
print(text1)

# 안녕하세요.
# 
# 반갑습니다.

print() 는 개행이 있기 때문에 띄워져 보인다.

readlines()

파일을 한줄씩 리스트로 가져온다.

# 파일을 읽기모드로 연다. 파일이 없으면 에러가 발생한다.
file_editor = open(file="test.txt", mode="r", encoding="utf-8")

# 파일을 읽는다.
text_list = file_editor.readlines()

# 파일에디터를 닫는다.
file_editor.close()

print(text_list)

# ['안녕하세요.\n', '반갑습니다.']

파일 삭제

1

파일이 없을 경우 에러가 발생한다.
if문이나 try문으로 처리하자.

import os

if os.path.exists("test.txt"):
    os.remove("test.txt")

2

파일이 없어도 메시지는 뜨지만 에러가 발생하지 않는다.

import os

os.system("rm test.txt")

폴더 및 파일 삭제시 -r 또는 -rf 를 이용한다.

import os

os.system("rm -r asdf/test.txt")

with 사용하기

에디터를 일일이 close 하기 어려울 경우 with를 사용한다.
(객체를 제거한다.)

with open(file="test.txt", mode="r", encoding="utf-8") as file_editor:
    text = file_editor.read()

print(text)

바이너리 파일 다루기

일반 바이너리 파일

with open(file="bin.txt", mode="bw") as file_editor:
    file_editor.write(bytes("a", encoding="utf-8"))

pickle 파일

객체 자체를 파일로 저장할 수 있다. (직렬화)

import pickle

with open(file="list.pickle", mode="bw") as file_editor:
    pickle.dump([1, 2, 3], file_editor)

다시 가져와보면 (역직렬화)

import pickle

with open(file="list.pickle", mode="br") as file_editor:
    my_list = pickle.load(file_editor)

print(my_list)

# [1, 2, 3]

ps

pickle 이외에도 json, marshal 등이 있다.
적절하게 사용하자.

profile
티스토리 블로그 https://ondolroom.tistory.com/

0개의 댓글