文件操作在相对路径中不起作用

File operations not working in relative paths

我正在开发具有相当简单文件结构的 python3 应用程序,但我在读取脚本中的文本文件时遇到问题,这两个文件结构的文件结构都低于脚本调用他们。绝对清楚,文件结构如下:

app/
|- cli-script
|- app_core/
   |- dictionary.txt
   |- lib.py

cli-script 调用 lib.py,而 lib.py 需要 dictionary.txt 做我需要它做的事情,所以它被打开并在 lib.py 中读取。

cli-script 的基础知识如下所示:

from app_core import lib
def cli_func():
  x = lib.Lib_Class()
  x.lib_func()

lib的问题区在这里:

class Lib_Class:
  def __init__(self):
    dictionary = open('dictionary.txt')

我遇到的问题是,虽然我有这个文件结构,但 lib 文件找不到字典文件,返回 FileNotFoundError。出于可移植性原因,我宁愿只使用相对路径,但除此之外我只需要使解决方案 OS 不可知。符号链接是我想到的最后一个选择,但我想不惜一切代价避免使用它。我有哪些选择?

因为您希望 dictionary.txt 出现在与 lib.py 文件相同的路径中,您可以执行以下操作。

而不是 dictionary = open('dictionary.txt') 使用

dictionary = open(Path(__file__).parent / 'dictionary.txt')

当您 运行 一个 Python 脚本时,涉及路径的调用是相对于您 运行 它们来自的位置执行的,而不是文件实际来自的位置。

__file__ 变量存储当前文件的路径(无论它在哪里),因此相关文件将是该文件的兄弟文件。

在你的结构中,__file__指的是路径app/app_core/lib.py,所以要创建app/app_core/dictionary.txt,你需要coup再down。

app/app_core/lib.py

import os.path

class Lib_Class:
  def __init__(self):
    path = os.path.join(os.path.dirname(__file__), 'dictionary.txt')
    dictionary = open(path)

或使用pathlib

path = pathlib.Path(__file__).parent / 'dictionary.txt'