[英]with open FileNotFoundError: [Errno 2] No such file or directory:
Here is the folder structure of my code:这是我的代码的文件夹结构:
project/
latplan/
__init__.py
model.py
samples/
text.txt
main2.py
lyrics/
main.py
Content of each file:每个文件的内容:
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 main2.py
#!/usr/bin/env python
import latplan
latplan.model.NN().load()
model.py模型.py
class NN():
x = 5
def load(self):
with open("samples/text.txt", "r") as f:
print("success")
When I execute main2.py (from project/ folder):当我执行main2.py (从项目/文件夹):
./main2.py
I get :我得到:
success成功
But when I execute main.py (from lyrics/ folder):但是当我执行main.py (来自歌词/文件夹)时:
./main.py
I get the error:我得到错误:
"\lyrics../project\latplan\model.py", line 6, in load with open("samples/text.txt", "r") as f: FileNotFoundError: [Errno 2] No such file or directory: 'samples/text.txt "\lyrics../project\latplan\model.py",第 6 行,在加载中使用 open("samples/text.txt", "r") as f: FileNotFoundError: [Errno 2] 没有这样的文件或目录: '样本/文本.txt
I can only modify main.py file, so how can I do so, in order to avoid this error ?我只能修改 main.py文件,那我该怎么做才能避免这个错误呢?
Thanks a lot非常感谢
If you can only modify main.py
, the only workable approach is to change the working directory on launch.如果只能修改main.py
,唯一可行的方法是在启动时更改工作目录。 After modifying sys.path
, you can add :修改sys.path
后,可以添加:
os.chdir('../project')
which will change your working directory for when it looks up new relative path names outside of import contexts (it will also affect import contexts, but only when the empty string is in sys.path
, which by default only happens when run interactively, or when the script is read from stdin
, neither of which are the expected case here).当它在导入上下文之外查找新的相对路径名时,它将更改您的工作目录(它也会影响导入上下文,但仅当空字符串位于sys.path
时,默认情况下仅在交互运行时发生,或者当该脚本是从stdin
读取的,这两种情况都不是这里的预期情况)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.