简体   繁体   English

FileNotFoundError:运行unittest python时

[英]FileNotFoundError : while running unittest python

For my new Python project, I followed the following directory structure as suggested by, http://docs.python-guide.org/en/latest/writing/structure/ 对于我的新Python项目,我遵循http://docs.python-guide.org/zh/latest/writing/structure/所建议的以下目录结构

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

Where trial.py's demo reads trial.text and perform some operation trial.py's demo在其中读取trial.text并执行一些操作的地方

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

The code works and tests works fine when I run it from project directory 当我从project目录运行代码时,代码有效,测试正常

The test throws file not found error on trial.txt when running from inside of tests directory tests目录内部运行时,该testtrial.txt上引发找不到文件的错误trial.txt

I have also added a context module for tests 我还添加了一个用于tests的上下文模块

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

import trial

Fixed it by adding this before opening the file 通过在打开文件之前添加此内容来修复它

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

You can do this to make it write 你可以这样做使它写

Make a python script in the Solution directory and name it as 解决方案目录中制作一个python脚本并将其命名为

name -> __init__.py

import trial

and save this file in the Solution directory 并将此文件保存在解决方案目录中

Now try to import Solution from test.py like this one right here: 现在,尝试从test.py 导入解决方案 ,就像这样在这里:

from Solution import trial
trial.main()

But make sure the code in the trial.py file in some function like main() and then you can call like 但是请确保使用main()之类的函数在trial.py文件中的代码,然后可以像这样调用

trial.main() 

For better understanding see this example of my directory 为了更好地理解,请参阅我的目录的此示例

在此处输入图片说明

在此处输入图片说明

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