Python 处理3 为什么当前工作目录有时不同?

Python processing 3 why is current working directory different sometimes?

我在为 Python 处理 mac 时有时会收到此错误。看似无缘无故,有时当前工作目录会变成您在图像中看到的内容,而有时它是 pyde 文件所在文件夹的工作目录。

关于为什么会发生这种情况的任何想法?

为了避免此类问题,我总是尽量使用绝对路径。我建议您尝试这样的文件路径:

import os

# This will be the path to your .py file
FILE_PATH = os.path.dirname(os.path.abspath(__file__))

# This will be the path to your text file, if it is in the same directory as the .py
LEVELS_FILE_PATH = os.path.join(FILE_PATH, "levels.txt")

然后,您可以:

而不是当前的 open 语句
f = open(LEVELS_FILE_PATH, 'r')