[英]Python import a module, receive a system cannot find the path specified error
我正在使用python 3.7.1,並且在我的項目中具有這樣的結構
project/
├── plugins
│ ├── __init__.py
│ └── plugin_one
│ ├── __init__.py
│ ├── process_json.py
│ └── data
│ └── cities
│ └── paris.json
│ └── new_york.json
└── test1.py
當我寫“ process_json.py”時,我從“數據/城市”目錄中一個接一個地讀取json文件,並打印出json字符串。
# do_plugin_one.py
import json
import os
def process_json_string():
file_path = 'data/cities'
for filename in os.listdir(file_path):
if filename.endswith('.json'):
with open(os.path.join(search_path, filename)) as f:
print(json.load(f))
process_json_string()
# output is a json string
如果我直接運行此腳本文件,它將運行正常。 但是我想要實現的是像這樣將process_json.py導入到test1.py中:
# test1.py
from plugins.plugin_one.process_json import process_json_string
process_json_string()
當我嘗試這樣做時,我得到了:
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'data/cities'
如果我正確理解它,那么在通過“ test1.py”導入時,工作路徑在“ test1.py”所在的位置。 所以我嘗試了:
# process_json.py
...
def process_json_string():
file_path = 'plugins/plugin_one/data/cities'
...
終於成功了。 但是,我想保留該文件以便能夠單獨運行。 在搜索文檔和頁面之后,我仍然不知道如何實現這一目標。 我什至嘗試過:
# process_json.py
...
file_path = 'plugins/plugin_one/data/cities'
...
if __name__ == '__main__':
file_path = 'data/cities'
...
我認為這樣的事情不是最佳的。
我也嘗試過使用相對路徑,但還是沒有運氣。 任何幫助,將不勝感激! 謝謝!
您正在使用相對路徑。 運行python項目時,當前的工作目錄被視為您運行的文件的目錄。
因此,當您直接運行process_json.py
,它將在project/plugins/plugin_one
搜索data/cities
,而當您在test1.py
導入process_json.py
時,它將在project/
搜索data/cities
。 如果使用絕對路徑,則不會有此問題。
但是,在大多數情況下,您不想直接放置絕對路徑,因此只需將__file__
目錄名連接到data/cities
,您將獲得絕對路徑:
file_path = os.path.join(os.path.dirname(__file__), 'data', 'cities')
如果您想要相對於process_json.py的路徑,則可以使用該模塊的file屬性,並從那里構建路徑:
# process_json.py
import os
datadir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data', 'cities')
當然,您也可以考慮將數據目錄移動到文件系統上的其他位置,而不是包本身(在* nix上,位於share/
下的某個位置),並根據需要使用環境變量來設置路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.