【发布时间】:2019-04-20 18:28:34
【问题描述】:
我试图让包内的模块在其目录中打开一个 txt 文件并读取其内容。
我的安排是这样的:
package
| __init__.py
| bar.py
| baz.py
| txt.txt
foo.py
这是txt.txt的内容
a()
这是baz.py的内容
def a():
with open("txt.txt") as file:
print(file.read())
这是bar.py的内容
from .baz import a
def b():
a()
print("b()")
这是__init__.py的内容
from .bar import b
def c():
b()
print("c()")
这是foo.py的内容
from package import c
c()
运行 foo.py 时,我希望得到
a()
b()
c()
但是我得到了这个错误
Traceback (most recent call last):
File "foo.py", line 2, in <module>
c()
File "(...my full path...)\package\__init__.py", line 3, in c
b()
File "(...my full path...)\package\bar.py", line 3, in b
a()
File "(...my full path...)\package\baz.py", line 2, in a
with open("txt.txt") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'txt.txt'
我将open 函数"txt.txt" 的参数更改为完整路径并且它起作用了,但这并不是真的有用,因为我必须使用相对路径,而且我不明白发生了什么。
有什么建议吗?
【问题讨论】:
-
foo.py正在从不存在相对路径text.txt的位置运行。如果foo.py是从与package目录相同的位置运行的,则使用package/text.txt作为文件路径。请记住:决定路径的是您的代码正在运行,而不是正在运行的代码所在的位置。 -
如果您有相对路径的问题,请使用绝对路径。模块的
__file__属性结合pathlib或os.path中的函数可能会有所帮助。
标签: python python-3.x