繁体   English   中英

FileNotFoundError:运行unittest python时

[英]FileNotFoundError : while running unittest python

对于我的新Python项目,我遵循http://docs.python-guide.org/zh/latest/writing/structure/所建议的以下目录结构

Project
      solution
          __init__.py
          trial.txt
          trial.py
      tests
          __init__.py
          test.py

trial.py's demo在其中读取trial.text并执行一些操作的地方

with open("trial.txt") as f:
    f.readlines()

当我从project目录运行代码时,代码有效,测试正常

tests目录内部运行时,该testtrial.txt上引发找不到文件的错误trial.txt

我还添加了一个用于tests的上下文模块

import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../solution')))

import trial

通过在打开文件之前添加此内容来修复它

file_path = (os.path.dirname(__file__))+"/trail.txt"
with open(filepath,"r") as f:
    f.readlines()

你可以这样做使它写

解决方案目录中制作一个python脚本并将其命名为

name -> __init__.py

import trial

并将此文件保存在解决方案目录中

现在,尝试从test.py 导入解决方案 ,就像这样在这里:

from Solution import trial
trial.main()

但是请确保使用main()之类的函数在trial.py文件中的代码,然后可以像这样调用

trial.main() 

为了更好地理解,请参阅我的目录的此示例

在此处输入图片说明

在此处输入图片说明

The file data.py and __init__.py are in the same directory. You can see here and try to solve.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM