【问题标题】:with open FileNotFoundError: [Errno 2] No such file or directory:打开 FileNotFoundError: [Errno 2] 没有这样的文件或目录:
【发布时间】:2022-07-21 23:06:15
【问题描述】:

这是我的代码的文件夹结构:

project/
    latplan/
         __init__.py
         model.py
    samples/
         text.txt
    main2.py
lyrics/
    main.py

每个文件的内容:

main.py

#!/usr/bin/env python
import sys
sys.path.append(r"../project")
import latplan

... = some other code where latplan module was needed, then:

latplan.model.NN().load()

main2.py

#!/usr/bin/env python
import latplan

latplan.model.NN().load()

model.py

class NN():
    x = 5
    def load(self):
        with open("samples/text.txt", "r") as f:
            print("success")

当我执行 main2.py (从项目/文件夹):

./main2.py

我明白了:

成功

但是当我执行 main.py (来自歌词/文件夹):

./main.py

我得到错误:

“\lyrics../project\latplan\model.py”,第 6 行,加载中 with open("samples/text.txt", "r") as f: FileNotFoundError: [Errno 2] No such file or directory: 'samples/text.txt

只能修改main.py文件,我该怎么做才能避免这个错误呢?

非常感谢

【问题讨论】:

  • 相对路径总是相对于当前工作目录...如果你在lyrics/ 那么samples/text.txt 是不正确的。你需要../samples/text.txt...

标签: python python-3.x


【解决方案1】:

如果您只能修改main.py,唯一可行的方法是在启动时更改工作目录。而不是完全改变sys.path,您可以将该行替换为:

os.chdir('../project')

这将为所有目的(模块查找和相对路径查找)更改您的工作目录。

【讨论】:

  • 好的,但实际上在“歌词”目录中还有其他文件和子文件夹(为了简单起见,我没有显示),所以我担心你的方法会阻止我调用代码片段来自“歌词”(执行 main.py 时)。或者我可以仅为 latplan.model.NN().load() 更改目录,然后返回“歌词”目录?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 2021-08-24
  • 2021-03-07
  • 2015-06-09
  • 2021-04-01
  • 2021-10-15
相关资源
最近更新 更多