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

使用Python从另一个目录访问文件时出错,python,Python,这是我的Python代码: 从插件导入插件 导入日志记录 进口yaml log=logging.getLogger('discord') def get_bot_前缀(): 使用open('HarTex/hartexConfig.yaml','r')作为前缀读取器: prefixValue=yaml.安全负载(prefixReader) prefixString=prefixValue['settings']['prefix'] 返回前缀字符串 prefix=get\u bot\u prefix

这是我的Python代码:

从插件导入插件
导入日志记录
进口yaml
log=logging.getLogger('discord')
def get_bot_前缀():
使用open('HarTex/hartexConfig.yaml','r')作为前缀读取器:
prefixValue=yaml.安全负载(prefixReader)
prefixString=prefixValue['settings']['prefix']
返回前缀字符串
prefix=get\u bot\u 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'
回溯(最近一次呼叫最后一次):
文件“C:/Users/85251/Documents/Discord Bots/Python/HarTex/bot.py”,第20行,在
从plugins.help导入帮助
文件“C:\Users\85251\Documents\Discord Bots\Python\HarTex\plugins\help.py”,第30行,在
prefix=get\u bot\u prefix()
文件“C:\Users\85251\Documents\Discord Bots\Python\HarTex\plugins\help.py”,第22行,在get\u bot\u前缀中
使用open('HarTex/hartexConfig.yaml','r')作为前缀读取器:
FileNotFoundError:[Errno 2]没有这样的文件或目录:“HarTex/hartexConfig.yaml”

我怎样才能修好它?或者我完全错在目录上了吗?

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


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

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

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


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

您的
hartexConfig.yaml
是否与
bot.py
位于同一目录中?是的,它是。。。我想知道这个问题是否与解决方案有关?因此,如果您从同一个目录运行它,请尝试使用
和open('hartexConfig.yaml','r')作为前缀读取器:
似乎您在不同的文件夹中运行代码,然后您会想。使用
print(os.getcwd())
查看它。您还可以检查当前文件夹中的文件
print(os.listdir())