Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

FileNotFoundError: [Errno 2] No such file or directory: '/data/tables/РасписаниеФКН_…

  1. User

    FileNotFoundError: [Errno 2] No such file or directory: '/data/tables/РасписаниеФКН_ осенний семестр 2024-2025 (2).xlsx' if i run run.py. if i run tables.py its working tables.py: import datetime from os.path import split

    from openpyxl.cell import MergedCell from openpyxl.worksheet.worksheet import Worksheet import openpyxl

    from data import config

    def get_sheet_rasp(): wb = openpyxl.load_workbook( r"/data/tables/РасписаниеФКН_ осенний семестр 2024-2025 (2).xlsx") sheet = wb.worksheets[0] return sheet print(get_sheet_rasp())

    def get_dict(): sheet = get_sheet_rasp() a = dict() for i in range(3, sheet.max_column): group = parser_merged_cell(sheet, 1, i) sub_group = parser_merged_cell(sheet, 2, i) item = parser_merged_cell(sheet, 3, i) profile = parser_merged_cell(sheet, 4, i) if parser_merged_cell(sheet, 4, i) not in [None, ""] else "Профиля нет."

        a.setdefault(group, {}).setdefault(sub_group, {})[item] = profile
    
    return a
    

    def get_schedule_by_column_week_day_of_week(column, week, day_of_week): sheet= get_sheet_rasp() day_of_week = str(day_of_week)

    # Читаем данные из первого столбца sheetRasp с учетом объединённых ячеек
    dataRasp = get_schedule()
    
    # Информация о группе (первые 4 строки)
    dataOfGroup = []
    for i in range(1, 5):
        time_data = str(dataRasp[i - 1]) if i - 1 < len(dataRasp) and dataRasp[i - 1] is not None else ""
        cell_value = parser_merged_cell(sheet, row=i, col=column)
        value_str = str(cell_value).replace("\n", "") if cell_value is not None else ""
        dataOfGroup.append([time_data, value_str])
    
    # Расписание (начиная с 5-й строки)
    dataOfShedule = []
    for i in range(5, sheet.max_row + 1):
        time_data = str(dataRasp[i - 1]) if i - 1 < len(dataRasp) and dataRasp[i - 1] is not None else ""
        cell_value = parser_merged_cell(sheet, row=i, col=column)
        if cell_value is not None:
            value_str = str(cell_value).replace("\n", "")
            dataOfShedule.append([time_data, value_str])
    
    # Фильтрация расписания по дню недели и четности недели
    returned = []
    for time_data, schedule_entry in dataOfShedule:
        time_parts = time_data.split()
        if len(time_parts) >= 3 and time_parts[0] == day_of_week and time_parts[2] == week:
            returned.append([time_data, schedule_entry])
    
    return dataOfGroup, returned
    

    def parser_merged_cell(sheet: openpyxl.worksheet.worksheet.Worksheet, row, col): cell = sheet.cell(row=row, column=col) if isinstance(cell, MergedCell): for merged_range in sheet.merged_cells.ranges: if cell.coordinate in merged_range: cell = sheet.cell(row=merged_range.min_row, column=merged_range.min_col) break return cell.value

    def generate_schedule_of_time(): sheet = get_sheet_rasp() dataShedule = ["Курс", "Группа", "Направление", "Профиль"] para = 1 chOrZn = "Числитель" for i in range(5, sheet.max_row): if not (parser_merged_cell(sheet, i, 1) is None or parser_merged_cell(sheet, i, 2) is None): dataShedule.append( f"{parser_merged_cell(sheet, i, 1)} {para} {chOrZn} {parser_merged_cell(sheet, i, 2).replace(' ', '')}") if chOrZn == "Знаменатель": para += 1 chOrZn = "Числитель" else: chOrZn = "Знаменатель"

        else:
            para = 1
            chOrZn = "Числитель"
            dataShedule.append("0")
    
    with open("../data/schedule", "w", encoding="utf-8") as f:
        f.write("\n".join(dataShedule))
    

    def get_schedule(): return list(i.replace("\n", "") for i in open("../data/schedule", "r", encoding="utf-8").readlines())

    def get_column_by_course_group_subgroup(course, group, subgroup): sheet = get_sheet_rasp() data = [] for col in range(1, sheet.max_column + 1): # Получаем значения ячеек с учётом объединения cell_course = parser_merged_cell(sheet, 1, col) cell_group = parser_merged_cell(sheet, 2, col)

        # Проверяем соответствие курса и группы
        if cell_course == course and cell_group == group:
            data.append(col)
    
    # Возвращаем колонку в зависимости от подгруппы
    if subgroup == "1 подгруппа":
        return data[0] if data else None
    elif subgroup == "2 подгруппа":
        return data[1] if len(data) > 1 else None
    else:
        return None
    

    main.py:

    import asyncio import sys from os import getenv

    import logging from aiogram import Bot, Dispatcher from aiogram.filters import CommandStart from aiogram.types import Message from dotenv import load_dotenv from app.handlers import router

    load_dotenv() TOKEN = getenv("BOT_TOKEN")

    bot = Bot(token=TOKEN) dp = Dispatcher()

    async def main(): dp.include_router(router) await dp.start_polling(bot)

    if name == 'main': logging.basicConfig(level=logging.INFO, stream=sys.stdout) asyncio.run(main())

  2. Assistant

    The FileNotFoundError you're encountering is due to the way the file path is specified in your tables.py script. Specifically, you're using an absolute path starting with /, which refers to the root directory of your filesystem. When you run tables.py, it might work because the current working directory and the path resolution context make the file accessible. However, when you run run.py or main.py, the script's working directory is different, and the absolute path doesn't point to the correct location.

    Here's what's happening:

    • Absolute Path Issue: The path "/data/tables/РасписаниеФКН_ осенний семестр 2024-2025 (2).xlsx" is interpreted as an absolute path starting from the root of your filesystem. Unless you have a directory named data at the root of your filesystem (like C:/data on Windows or /data on Unix/Linux), this path will not point to the correct file.

    • Working Directory Differences: When you run tables.py directly, Python's current working directory might be set such that relative paths (even those starting with /) resolve differently. But when you run run.py or main.py, the working directory is likely different, causing the file path resolution to fail.

    Solution:

    To fix this issue, you should:

    1. Use Relative Paths: Instead of an absolute path, use a path that's relative to your script's location.

    2. Compute Absolute Paths Dynamically: Use Python's os.path module to build the file path based on the script's directory. This ensures that the path will be correct no matter where the script is run from.

    3. Avoid Hardcoding Paths: Hardcoding paths can lead to issues when the code is run in different environments or directories.

    Here's how you can modify your get_sheet_rasp function:

    import os
    import openpyxl
    
    def get_sheet_rasp():
        # Get the directory of the current script
        current_dir = os.path.dirname(os.path.abspath(__file__))
        # Construct the relative path to the Excel file
        file_path = os.path.join(current_dir, 'data', 'tables', 'РасписаниеФКН_ осенний семестр 2024-2025 (2).xlsx')
        # Use the constructed path to load the workbook
        wb = openpyxl.load_workbook(file_path)
        sheet = wb.worksheets[0]
        return sheet
    

    Explanation:

    • os.path.abspath(__file__) gives you the absolute path of the current script.
    • os.path.dirname(...) gives you the directory containing the script.
    • os.path.join(...) constructs a path by joining directory names in a platform-independent way.
    • By constructing the path relative to the script's directory, you ensure that the file is found regardless of the current working directory when the script is run.

    Additional Notes:

    • Check File Location: Make sure that your Excel file is actually located at the path you construct. If your project structure is different, adjust the os.path.join arguments accordingly.

    • Use Raw Strings Carefully: When dealing with paths, especially on Windows, be cautious with backslashes (\). Using raw strings (r"...") can help avoid issues with escape characters.

    • Avoid Starting Paths with '/': Unless you intend to refer to the root directory of the filesystem, avoid starting paths with '/'. It's safer to build paths relative to known locations.

    Final Advice:

    By making these changes, you should be able to run your code from any script (tables.py, run.py, main.py, etc.) without encountering the FileNotFoundError, as the file paths will be correctly resolved relative to your script's location.