[英]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
目錄內部運行時,該test
在trial.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.