Questions about Python CSV... ValueError: I/O operation on closed file.

Asked 2 years ago, Updated 2 years ago, 71 views

Hello, I am a student who is making coding difficult while studying Python. I'm coding with Python using Raspberry Pie, and I'm trying to save a CSV file. There was a problem here.

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

An error similar to has occurred.

I tried using f.close() to close the file in a similar problem posted by others in a foreign forum, but the error was not resolved.

I'm still studying, so I'm not good enough. But I want to do what I'm doing as much as possible.

I'm going to upload the code I used for Raspberry Pie together.

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()

raspberry-pi csv python

2022-09-21 10:01

1 Answers

If you leave the with syntax block of with open(filepath) as f:, the file is automatically closed when you leave the block. The part that writes with csv in the while statement at the back should also be included in the with block.


2022-09-21 10:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.