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

问题描述 投票:0回答:2

我正在使用一个非常简单的文件结构来开发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不可知。符号链接是我找到的最后选择,但我不惜一切代价避免使用它。我有什么选择?

python python-3.x file-io io file-not-found
2个回答
0
投票

由于您期望dictionary.txtlib.py文件位于相同的路径中,因此您可以执行以下操作。

代替dictionary = open('dictionary.txt')使用

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

0
投票

当您运行Python脚本时,涉及路径的调用是相对于您从何处运行的,而不是相对于文件实际所在的位置。

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

在您的结构中,__file__指的是路径app/app_core/lib.py,因此要创建app/app_core/dictionary.txt,您需要先升高然后降低。

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'
© www.soinside.com 2019 - 2024. All rights reserved.