파일은 바이너리 파일(binary file)
과 텍스트 파일(text file)
로 나누어서 다룬다.
바이너리 파일은 데이터의 저장과 처리를 목적으로 0과 1의 이진 형식으로 인코딩된 파일이며,
텍스트 파일은 사람이 알아볼 수 있는 문자열로 이루어진 파일이다.
open() / close()
# 파일 열기
file_object = open(str: path, str: mode)
# 파일 닫기
file_object.close()
mode 지정 방식
모드 | 설명 |
---|---|
w | 파일이 존재하지 않으면 새로 생성 후 쓰기/ 파일이 존재하면 파일 내용을 비우고 쓰기 |
a | 기존 파일 뒤에 이어서 쓰기 |
x | 새로운 파일을 생성/ 파일이 이미 존재하면 Error 발생 |
r | 파일 읽기 |
코드 작성 시 파일을 열고 닫지 않는 실수를 방지하기 위해 with 키워드를 사용하며, with 구문이 종료될 때 자동으로 닫히게 된다.
with open(str: path, str: mode) as file_object:
code
read() / write()
# 파일 읽기
file_object.read()
# 파일 쓰기
file_object.write(str)
예제 데이터 생성
# random 모듈을 이용하여 데이터 구성
import random
# 알파벳 리스트 생성
alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
# 파일 열기
with open("C:\\Users\\wooju\\Desktop\\wooju\\file_example.txt","w") as file:
for i in range(100):
# 랜덤값으로 변수 생성
first_str = random.choice(alphabet)
first_int = random.randrange(50)
second_str = random.choice(alphabet) + random.choice(alphabet)
second_int = random.random()
# 텍스트 쓰기
file.write("{}, {}, {}, {}\n".format(first_str,first_int,second_str,second_int))
반복문으로 한 줄씩 읽기
# 파일 열기
with open("C:\\Users\\wooju\\Desktop\\wooju\\file_example.txt","r") as file:
for line in file:
# 변수를 생성하여 한줄씩 넣기
first_str,first_int,second_str,second_int = line.strip().split(", ")
# 한 줄씩 출력
print(f"{first_str} {first_int} {second_str} {second_int}")