![](/img/trans.png)
[英]How to get to a file in sister directory with python without knowing the full path
[英]Get the full path to the directory a Python file is contained in
實際上,我從先前的答案中找到了我的主要問題“獲取包含Python文件的目錄的完整路徑”的解決方案: 查找當前目錄和文件的目錄 。
如果我運行我的整個腳本(換句話說,熱鍵F5),則答案中的以下代碼將運行良好。
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
但是,如果我只選擇上面代碼的兩行並運行它,換句話說,就是熱鍵F9。 然后,我將收到以下錯誤:
NameError: name '__file__' is not defined
因此,如果有人碰巧知道為什么會發生錯誤,請簡要說明。
非常感謝!
順便說一下,我使用了Spyder(Python 2.7)。
在Spyder或任何交互式python進程內部,未定義常量__file__
。
當您運行整個腳本時,Spyder基本上運行以下命令:
$ python script.py
同時,如果選擇這兩行,則更像是先輸入一個交互式python進程,然后解釋以下語句:
$ python
Python 2.7.13 (default, Jun 12 2017, 17:25:44)
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> dir_path = os.path.dirname(os.path.realpath(__file__))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
>>>
就是這樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.