使用Python从另一个目录访问文件时出错

2024-06-28 11:36:51 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的Python代码:

from plugin import Plugin

import logging

import yaml

log = logging.getLogger('discord')

def get_bot_prefix():
    with open('HarTex/hartexConfig.yaml', 'r') as prefixReader:
        prefixValue = yaml.safe_load(prefixReader)

        prefixString = prefixValue['settings']['prefix']

    return prefixString


prefix = get_bot_prefix()

但是,我在访问文件时出错:

Traceback (most recent call last):
  File "C:/Users/85251/Documents/Discord Bots/Python/HarTex/bot.py", line 20, in <module>
    from plugins.help import Help
  File "C:\Users\85251\Documents\Discord Bots\Python\HarTex\plugins\help.py", line 30, in <module>
    prefix = get_bot_prefix()
  File "C:\Users\85251\Documents\Discord Bots\Python\HarTex\plugins\help.py", line 22, in get_bot_prefix
    with open('HarTex/hartexConfig.yaml', 'r') as prefixReader:
FileNotFoundError: [Errno 2] No such file or directory: 'HarTex/hartexConfig.yaml'

我怎样才能修好它?还是我的目录完全错了


Tags: pyimportyamlgetprefixbotlineusers
2条回答

如果您是从HarTex的父目录调用脚本,那么脚本应该可以工作,也许您是从其他工作目录运行它

您还可以尝试使用完整路径打开文件,因为这可能很容易检查

错误很明显。您应该使用绝对路径而不是相对路径

例如home/Prakash/Desktop/test12/test.yaml

您的代码肯定能工作,一旦您像这样更改路径

相关问题 更多 >