0

I want the bot to create a file it is not doing that in

f = open(f"json/guilds/db-gc/{name}.json", 'w')
print("{\"words\":[]}", file = f)

This Line Please Help me

@client.command()
async def chat_filter(ctx, val = None):
  guild = ctx.guild
  with open(f"json/guilds/config.json", "r") as f:
    load = json.load(f)
  if guild.id in load["ids"]:
    print("The Guild Is Registerred")
  elif not guild.id in load["ids"]:
    name = ctx.guild.id
    name = str(float(name))
    id = str(guild.id)
    f = open(f"json/guilds/db-gc/{name}.json", 'w')
    print("{\"words\":[]}", file = f)
    with open(f"json/guilds/config.json", "r") as f:
      l = json.load(f)
    l["ids"].append(ctx.guild.id)
    with open(f"json/guilds/config.json", "w") as f:
      json.dump(l, f)
  else:
    raise Exception("Some Error")

Error

Ignoring exception in command chat_filter:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 52, in chat_filter
    f = open(f"json/guilds/db-gc/{name}.json", 'w')
FileNotFoundError: [Errno 2] No such file or directory: 'json/guilds/db-gc/8.205884699055227e+17.json'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: 'json/guilds/db-gc/8.205884699055227e+17.json'

The bot is not really creating the file in that line please help me if you guys cam i will be really thankfull to you

Thankyou

  • What does it do? Do you get an error? Are you sure those paths exist? `open` will not create the intermediate directories. – Tim Roberts Aug 23 '21 at 03:56
  • `FileNotFoundError` can happen when the parent directories of your file don't exist (i.e. the json/guilds/db-gc folder). Also, it might be safer to use absolute paths. – Jan Wilamowski Aug 23 '21 at 06:51
  • Does this answer your question? [Python using open (w+) FileNotFoundError](https://stackoverflow.com/questions/31414263/python-using-open-w-filenotfounderror) – Jan Wilamowski Aug 23 '21 at 06:53

3 Answers3

0

Use "a+" instead of "w", this should fix it.

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Also consider, that you should open your file like this:

with open(f"json/guilds/db-gc/{name}.json", 'a+') as f:
   # Do something with the file

Note: The file will close automatically at the end of the block.

Maik Hasler
  • 1,064
  • 6
  • 36
0

Create file

`open` can create a new file if the second parameter is `'w'`, but it can't create a new path/directory.
>>> File = open("C:\path\to\file.json", 'w')
>>>

It will work if C:\\path\to was created yet.
Else, it won't.

There's a way to understand if a file exists:

>>> from pathlib import Path
>>> Path('C:\\path\to\file.json').is_file()
True

Create directory

But your problem isn't with the file, but with the directory, so you should try this:
>>> from os import path, makedirs
>>> if path.exists(r"C:\\path\to\file"):
           makedirs(r"C:\\path\to\file")
>>>

Look at this to know more.

Attention!

Also, it might be safer to use absolute paths.
– Jan Wilamowski

He's right, creating a new directory for each file isn't really elegant...
also because of inserting a guild ID in the directory name...

In conclusion

If it worked, accept my answer.
If it didn't work, say me in the comments what went wrong.
Hope it will work :)
FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
0

The open("directory","w") thing doesnt create a new file. To create one just simply do open("directory","a")