본문 바로가기
Python

Python 기초 #4: 파일 입출력 & 데이터 처리

by My Course 2025. 5. 7.

"센서 데이터를 저장하고, 다시 불러와보자"

  • .txt, .csv 파일 읽고 쓰기
  • with open() 구조로 안전하게 파일 다루기
  • 로봇 센서 데이터 저장 및 로깅 응용 예시

1. 텍스트 파일에 데이터 저장하기

로봇이 측정한 거리 데이터를 .txt 파일에 저장해보겠습니다.

# 거리 데이터 저장 예제

distance_data = [45, 48, 50, 47, 49]

with open("distance_log.txt", "w") as file:
    for d in distance_data:
        file.write(str(d) + "\n")

print("저장 완료!")

결과: distance_log.txt 파일이 생성되고, 각 값이 한 줄씩 저장됨


2. 텍스트 파일 읽기 (readline, readlines)

저장된 데이터를 다시 읽어올 수 있습니다.

# 파일에서 데이터 읽기

with open("distance_log.txt", "r") as file:
    lines = file.readlines()

# 문자열 → 숫자로 변환
distances = [int(line.strip()) for line in lines]
print("읽은 거리 값:", distances)

출력 예시:

읽은 거리 값: [45, 48, 50, 47, 49]

3. CSV 파일 저장하기

CSV는 데이터를 행/열 구조로 저장하는 데 적합합니다.
예를 들어 (시간, 거리) 데이터를 저장해보겠습니다.

# CSV로 (시간, 거리) 저장

data = [
    (1, 45),
    (2, 48),
    (3, 50),
    (4, 47),
    (5, 49)
]

with open("sensor_log.csv", "w") as file:
    file.write("time,distance\n")
    for t, d in data:
        file.write(f"{t},{d}\n")

print("CSV 저장 완료!")

4. CSV 데이터 읽고 분석하기

# CSV 읽기

with open("sensor_log.csv", "r") as file:
    lines = file.readlines()

data = []
for line in lines[1:]:  # 첫 줄은 헤더니까 건너뜀
    time_str, dist_str = line.strip().split(",")
    data.append((int(time_str), int(dist_str)))

print("불러온 데이터:", data)

실전 응용: 센서 로그 파일 저장 + 확인

import time
import random

with open("log.txt", "w") as f:
    for i in range(5):
        distance = random.randint(40, 60)
        timestamp = time.time()
        f.write(f"{timestamp},{distance}\n")
        time.sleep(1)

print("센서 로그 저장 완료")

로봇이 주행 중 실시간으로 거리 측정값을 기록할 때 사용할 수 있습니다!


정리

작업함수/구문설명
텍스트 쓰기 open("file.txt", "w") 한 줄씩 저장
텍스트 읽기 readline(), readlines() 리스트로 가져오기
CSV 저장 .csv 확장자 + , 구분 표 형식 저장
안전한 파일 사용 with open(...) 자동 닫힘 처리로 안전