@jwxee

FileNotFoundError: [Errno 2] No such file or directory: 'reports.json' что делать?

Бот на discord.py, выдаёт такую ошибку: with open('reports.json', encoding='utf-8') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'reports.json' при запуске бота

import json
from cgi import print_form
from http import client
from itertools import count
from multiprocessing.dummy import active_children
from pydoc import describe
from sys import prefix
from turtle import title, width
import discord
from discord.ext import commands
from config import settings
import os
import io
import contextlib



with open('reports.json', encoding='utf-8') as f:
    try:
        report = json.load(f)
    except ValueError:
        report = {}
        report['user'] = []


bot = commands.Bot(command_prefix = settings['prefix']) # Так как мы указали префикс в settings, обращаемся к словарю с ключом prefix.

@bot.command() # Не передаём аргумент pass_context, так как он был нужен в старых версиях.
async def hello(ctx): # Создаём функцию и передаём аргумент ctx.
    author = ctx.message.author # Объявляем переменную author и записываем туда информацию об авторе.

    await ctx.send(f'Hello, {author.mention}!') # Выводим сообщение с упоминанием автора, обращаясь к переменной author.

@bot.event
async def on_ready():
    print('READY')
    await bot.change_presence(active=discord.Game(name=f'{prefix}help'))


@bot.command()
async def embed(ctx):
    embed = discord.Embed(
        title = 'msg',
        description = 'msg'
    )
    await ctx.send(embed=embed)

@bot.command()
async def msg(ctx, arg):
    if arg == 'test':
        await ctx.send('TEST')
        await ctx.delete()

@bot.command()
async def chcreate(ctx, cout):
    if int(ctx.author.id) in administrators:
        for i in range(int(count)):
            create = 0
            try:
                await ctx.guild.create_text('для видео :)')
                await ctx.message.add_reaction('✅')
            except:
                print('канал не был создан')
            else:
                create+=1
                embed = discord.Embed(
                    title = 'канал успешно создан',
                    description = ' как дела?)'
                )
                await ctx.author.send(embed=embed)


@bot.command(pass_context = True)
@has_permissions(manage_roles=True, kick_members=True)
async def warn(ctx, user: discord.User,*reason: str):
    if not reason:
         await ctx.send('я не могу отправить жалобу, вы не указали причину')
         return
    reason = ''.join(reason)
    for current_user in report['user']:
        if current_user['name'] == user.name:
            current_user['reason'].append(reason)
            break
    else:
        report['users'].append({
            'name': user.name,
            'reasons': [reason,]
        })    
    with open('reports.json', 'w+') as f:
        json.dump(report,f)
    embed = discord.Embed(
        title = 'вы подали жалобу',
        description = 'жалоба на участника {user.name} была отправлена',
        colour = discord.Colour.from_rgb(100,0,0) 
    )
    await ctx.send(embed=embed)
    await ctx.message.delete()

@bot.command()
async def eval(ctx, *, code):
    if int(ctx.author.id) in administrtors:
        str_obj = io.StringIO()
    try:
        with contexlib.redirect_stdout(str_obj):
            exec(code)
    except Exception as e:
            return await ctx.send(f"```{e.__class__.__name__}:{e}```")
            await ctx.send(f'успех! {str_obj.getvaule()}')
    else:
        await ctx.send('у вас нет прав на редактирование кода')


@bot.command(pass_contex=True)
async def clear(ctx, limit):
    if int(ctx.author.id) in administrators:
        await ctx.message.delete()
        limit = int(limit)
        delete = await ctx.channel.purge(limit=limit)
        await ctx.send(f'удалено {delete} сообщений')

    
bot.run(token)
  • Вопрос задан
  • 483 просмотра
Пригласить эксперта
Ответы на вопрос 2
@denisromanenko
А файл точно есть в файловой системе? С самим кодом открытия проблем нет, просто ошибка чтения файла не обрабатывается.

Как я понял, в самом начале бота файла reports.json может и не быть, тогда создаётся пустой объект в памяти. Но первая строка "with open" не учитывает это
Ответ написан
Комментировать
Либо создать сам файл reports.json, либо сменить режим открытия файла.

По умолчанию open() открывает файл в режиме r

SnUmmeg.png

Стандартный режим - 'r' (открыть для чтения текста, синоним 'rt'). Режимы 'w+' и 'w+b' открывают и очищают файл. Режимы 'r+' и 'r+b' открывают файл без очистки.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы