簡體   English   中英

Python 3 - 問題導入模塊 - 從父目錄 - 包含文件描述符

[英]Python 3 - Issue importing module - from Parent Directory - that contains File Descriptor

我無法執行我認為應該是從文件的父目錄簡單導入 python3 模塊的操作。 我可以讓模塊導入從父目錄正常工作,直到我將文件描述符引入要導入的文件。

下面的示例#1 是一個“工作正常”的場景,#2 是我希望得到建議的有問題的場景。

#1 - 工作正常

應用目錄結構:

├── app
│   └── app.py
├── config.py

文件內容:

# app.py
import sys
sys.path.insert(0, '../')
from config import Config as conf

foo = conf.foo

if __name__ == '__main__':
    print('hello from app main')
    print(f'foo is --> {foo}')


#config.py
class Config():
    foo = 'bar'

運行:

$ pwd
app/
$ python app.py
hello from app main
foo is --> bar

#2 - 不工作/失敗

應用目錄結構:

├── app
│   └── app.py
├── config.py
└── foo.txt <-- **Introduced new file here**

文件內容:

# app.py
import sys
sys.path.insert(0, '../')
from config import Config as conf

foo = conf.foo

if __name__ == '__main__':
    print('hello from app main')
    print(f'foo is --> {foo}')

# config.py
class Config():
    with open('foo.txt', 'rt') as f:
        foo = f.readline().rstrip()   
    
# foo.txt
bar

運行:

$ pwd
app/

$ python app.py
Traceback (most recent call last):
  File "app.py", line 3, in <module>
    from config import Config as conf
  File "../config.py", line 1, in <module>
    class Config():
  File "../config.py", line 2, in Config
    with open('foo.txt', 'rt') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'foo.txt'

我在這里做錯了什么? 請注意,盡管出現“FileNotFoundError”錯誤消息,但實際上 foo.txt確實存在於父目錄中。

$ cat ../foo.txt
bar

謝謝。

我在這里做錯了什么?

您正在使用相對路徑。 這個:

open("foo.txt")

將在當前工作目錄中查找 foo.txt ,無論此時它是什么(這意味着它可以是任何東西,你永遠不應該對它做任何假設)。

請注意,盡管出現“FileNotFoundError”錯誤消息,但實際上 foo.txt 確實存在於父目錄中。

是的,它存在於父目錄中,但不存在於當前目錄中。

這里的規范解決方案是使用os.path函數和__file__魔術變量重建正確的路徑:

# config.py
import os

def read_foo():
    # build the full path to the current file
    here = os.path.abspath(__file__)
    # extract the directory path
    dirpath = os.path.dirname(here)
    # foo.txt is supposed to be in the same directory:
    foopath = os.path.join(dirpath, "foo.txt")
    with open(foopath) as f:
        return f.readline().rstrip()

現在您可以安全地從任何其他模塊調用config.read_foo() ,無論當前工作目錄是什么。

附帶說明:在class語句塊中讀取文件可能不是一個好主意 - 並不是說​​它在 Python 中是非法的,但它確實是一種設計味道......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM