Home > Software engineering >  ValueError: I/O operation on closed file. What's wrong with my code?
ValueError: I/O operation on closed file. What's wrong with my code?

Time:11-30

I have a problem with my code, and i don't know how to fix it. I found many similar questions but none of them solved my problem. I'm using Visual Studio Code as a code editor. Here is my code:

import discord
import json

with open('config.json') as config_file:
    config = json.load(config_file)

with open('data.json', 'r ') as data_file:
    data = json.load(data_file)

client = discord.Client()

@client.event
async def on_ready():
    print("Logged in as "   str(client.user))

@client.event
async def on_message(msg):
    if msg.author == client.user: return

    if msg.content == '!gcsetup':
        server_json_content = {}
        server_json_content["channel"] = msg.channel.id
        webhook = await msg.channel.create_webhook(name="name")
        server_json_content["webhook"] = webhook.url
        data.append(server_json_content)
        data_file.seek(0)
        json.dump(data, data_file)

client.run(config["token"])

I think the error is here:

    if msg.content == '!gcsetup':
        server_json_content = {}
        server_json_content["channel"] = msg.channel.id
        webhook = await msg.channel.create_webhook(name="name")
        server_json_content["webhook"] = webhook.url
        data.append(server_json_content)
        data_file.seek(0)
        json.dump(data, data_file)

According to the error error message:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "E:\Dev\main.py", line 26, in on_message
    data_file.seek(0)
ValueError: I/O operation on closed file.

CodePudding user response:

data_file variable exists only in with open('data.json', 'r ') as data_file: block therefore you can not use it outside of with.
Try to write

data_file = open('data.json', 'r ')
data = json.load(data_file)

Instead of

with open('data.json', 'r ') as data_file:
    data = json.load(data_file)

CodePudding user response:

When you use the with open()... statement to open a file handle, you implicitly close the handle at the end of the with block. Thus, when you call data_file.seek you are attempting to perform an I/O operation on a closed file, as the error message indicates.

The easiest solution is just to reopen the file for writing when doing the dump. This also obviates the need to seek to the beginning of the file, as this will be the default behavior when you open in writing mode.

    if msg.content == '!gcsetup':
        server_json_content = {}
        server_json_content["channel"] = msg.channel.id
        webhook = await msg.channel.create_webhook(name="name")
        server_json_content["webhook"] = webhook.url
        data.append(server_json_content)
        with open('data.json', 'w') as data_file:
            json.dump(data, data_file)

While you could also instead not use a with block (and thus never close the file handle), it's best practice not to keep lots of open file handles for the entirety of your discord server

  • Related