#πŸ”’ Getting an Value error in my code for file handling with CSV files

13 messages Β· Page 1 of 1 (latest)

shell creek
#

code: ```py
import csv

def read_file(filename):
try:
with open(filename, "r", newline="") as f1:
return f1
except FileNotFoundError:
print("File not found")
return None

def print_averages(fileobj):
if fileobj is None:
return

a = csv.reader(fileobj)
next(a)  # Skip header row

collection_of_grades = []
for i in a:
    for j in range(len(i)):
        if j in (1, 2, 3):  # Check if the column index is 1, 2, or 3
            collection_of_grades.append(float(i[j]))

avg = sum(collection_of_grades) / len(collection_of_grades)
print("Average grade:", avg)

filename = r"C:\Users\blufl\OneDrive\Desktop\CMPT120\Actual code\grades.csv"
def main(filename):
fileobj = read_file(filename)
if fileobj:
print_averages(fileobj)
else:
print("Unable to open file:", filename)

main(filename)


Error message: ```Exception has occurred: ValueError
I/O operation on closed file.
  File "C:\Users\blufl\OneDrive\Desktop\CMPT120\Actual code\lab7p1.py", line 15, in print_averages
    a = csv.reader(fileobj)
        ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\blufl\OneDrive\Desktop\CMPT120\Actual code\lab7p1.py", line 31, in main
    print_averages(fileobj)
  File "C:\Users\blufl\OneDrive\Desktop\CMPT120\Actual code\lab7p1.py", line 35, in <module>
    main(filename)
ValueError: I/O operation on closed file.```
summer wrenBOT
#

@shell creek

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

shell creek
#

this was an assignment i should add which required me to have a diff "file reading" function. I havent ever done this way which is why im encountering so many issues. Ive tried a number of different things such as asking chatgpt etc..

quiet wagon
#

you open a context manager, and then leave the context (using return), that closes the file

#

just return a plainly opened file if you want it to stay opened

zinc tundra
shell creek
#

oh really? thats it? wow

#

tysm ill just try it out

#

it worked tysm i appreciate your help @quiet wagon and @zinc tundra

zinc tundra
#

πŸ‘ If all is good, !close to close this post.

foggy carbon
#

and remember to close the file when you're down with it too since you don't have the context manager to help you with that anymore

summer wrenBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.