运行 Python Ubuntu 上的机器人(未找到文件或目录?)

Running Python bot on Ubuntu (file or directory not found?)

我 运行 我的 windows 机器上有一个 discord.py 机器人,但我不能 运行 Ubuntu 上的同一个机器人。我收到此行的“找不到文件错误”,这是机器人中最早的错误之一:

storm = json.load(open(r'jsons\storms.json', 'r'))['wind']

但它确实存在。这是回溯:

File "/root/bot/utility.py", line 6, in <module>
  storm = json.load(open(r'jsons\storms.json', 'r'))['wind']
FileNotFoundError: [Errno 2] No such file or directory: 'jsons\storms.json'

该机器人在我的 Windows 机器上工作,所以我假设 Ubuntu 或其他东西存在一些差异,因为我已将完整的机器人和所有文件复制到 Ubuntu 系统.

ubuntu 使用 '/' 而不是 '\'。所以而不是:

storm = json.load(open(r'jsons\storms.json', 'r'))['wind']

使用:

storm = json.load(open(r'jsons/storms.json', 'r'))['wind']

应该可以。

您正在使用带有反斜杠 \ 的 hard-coded Windows 路由,在 Unix/Linux 中是斜杠 /.

您可以使用 os.path.sep 访问正确的分隔符,它会 return \ 在 Windows 和 / 其他地方。

但可移植的方法是使用 os.path 中的连接函数,如下所示:

import os

storms_path = os.path.join('jsons', 'storms.json')
storm = json.load(open(storms_path, 'r'))['wind']

这将使用正确的分隔符来格式化您的路径,并将避免您在构建自己的路径时可能遇到的一些问题。

os.path docs here

不是硬编码 windows 或 linux 样式路径,您可能希望通过 python 使用 pathlib 标准库切换到更健壮的实现:https://docs.python.org/3/library/pathlib.html

一个最小的例子是这样的:

from pathlib import Path
folder = Path("add/path/to/file/here/")
path_to_file = folder / "some_random_file.xyz"
f = open(path_to_file)

请注意如何在初始化 Path 对象后轻松使用 / 运算符来附加例如文件名。

对于 json 文件的情况:

import json
from pathlib import Path
folder = Path("jsons/")
path_to_file = folder / "storms.json"
storm = json.load(open(path_to_file, 'r'))['wind']