파이썬 CSV 관련 질문.. ValueError: I/O operation on closed file.

조회수 4919회

안녕하세요. 파이썬을 공부하면서 코딩을 어렵게 어렵게 해나가고 있는 학생입니다. 지금 라즈베리파이를 이용하면서 파이썬으로 코딩을 하고 있는데, CSV파일을 저장하려하고 있습니다. 여기서 문제가 발생했습니다.


'''Traceback (most recent call last):
  File "test.py", line 47, in <module>
    csv_output.writerow(row)
ValueError: I/O operation on closed file.'''

와 같은 에러가 발생했습니다.

외국 포럼에서 다른 사람들이 올린 비슷한 문제에서 파일을 닫으라 하는데 f.close()를 사용해보았지만 에러가 해결되지 않았습니다.

아직 공부하는 중이라 많이 부족합니다. 하지만 지금하고 있는 일을 가능한 해내고 싶습니다.

라즈베리파이에 사용한 코드를 같이 올려봅니다.


import RPi.GPIO as GPIO
from adxl345 import ADXL345
import time
from sys import version_info
from datetime import datetime
import csv
import os

adxl345 = ADXL345()

relayPin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(relayPin, GPIO.OUT, initial=GPIO.HIGH)

print("Relay open...")
GPIO.output(relayPin, GPIO.HIGH)

print("Program is running...")
print("Program ")
junk = input("Press Enter to begin\n")
print("Waiting 20 seconds before activating relay")

count = 667  # increase this number by 10 for every second extra to want to record data for.
time.sleep(20)

filename = '/home/pi/logfiles/data_log.csv'
with open(filename, 'w', newline="") as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(["Time", "Accel"])

print("Relay close...")
GPIO.output(relayPin, GPIO.LOW)
time.sleep(20)

while count > 0:
    axes = adxl345.getAxes(True)
    print("ADXL345 on address 0x%x:") % (adxl345.address)
    x = (axes['x'])
    y = (axes['y'])
    z = (axes['z'])

    print("   x = ", x)
    print("   y = ", y)
    print("   z = ", z)

    row = [datetime.now().strftime("%Y-%m-%d %H:%M:%S"), x, y, z]
    csv_output.writerow(row)
    count = count - 1
    time.sleep(0.05)

print("End program")
GPIO.output(relayPin, GPIO.HIGH)
GPIO.cleanup()

1 답변

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)