[python 기초] 파일 처리

cosmos-JJ·2023년 11월 13일
0

Python

목록 보기
11/11

파일 처리

파일은 바이너리 파일(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 구문이 종료될 때 자동으로 닫히게 된다.

with open(str: path, str: mode) as file_object:
	
    code

📌 파일 읽기/쓰기

read() / write()

# 파일 읽기
file_object.read()
# 파일 쓰기
file_object.write(str)

📌 for문을 이용하여 텍스트 한 줄씩 읽기

예제 데이터 생성

# 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}")

참고

  • 혼자서 공부하는 파이썬(윤인성 지음)
profile
🤍도전하는 건 즐거워요🤍

0개의 댓글