簡體   English   中英

如何導入一個模塊,該模塊在與模塊相同的目錄中打開文件?

[英]How to import a module which opens a file in the same directory as the module?

我試圖在包dictionary中的模塊dict.py中調用函數is_english_word 這是層次結構:

DataCleaning
|___ text_cleaner.py
|___ dictionary
     |___ dict.py
     |___ list_of_english_words.txt

為了澄清,我在一個名為dictionary包中有dict.pylist_of_english_words.txt

這是用text_cleaner.py編寫的import語句:

import DataCleaning.dictionary.dict as dictionary

並且,這是用dict.py編寫的代碼:

import os

with open(os.path.join(os.path.dirname(os.path.realpath('__file__')), 'list_of_english_words.txt')) as word_file:
    english_words = set(word.strip().lower() for word in word_file)


def is_english_word(word):
    return word.lower() in english_words

但是當我運行text_cleaner.py文件時,它顯示導入錯誤,因為找不到list_of_english_words.txt

Traceback (most recent call last):
  File "E:/Analytics Practice/Social Media Analytics/analyticsPlatform/DataCleaning/text_cleaner.py", line 1, in <module>
    import DataCleaning.dictionary.dict as dictionary
  File "E:\Analytics Practice\Social Media Analytics\analyticsPlatform\DataCleaning\dictionary\dict.py", line 3, in <module>
    with open(os.path.join(os.path.dirname(os.path.realpath('__file__')), 'list_of_english_words.txt')) as word_file:
FileNotFoundError: [Errno 2] No such file or directory: 'E:\\Analytics Practice\\Social Media Analytics\\analyticsPlatform\\DataCleaning\\list_of_english_words.txt'

但是當我運行dict.py代碼本身時,它沒有顯示任何錯誤。 我可以清楚地看到os.path.dirname(os.path.realpath('__file__'))指向text_cleaner.py目錄而不是dict.py 如何導入我的模塊dict.py獨立於它的調用位置?

問題是您將字符串'__file__'傳遞給os.path.realpath而不是變量__file__

更改:

os.path.realpath('__file__')

至:

os.path.realpath(__file__)

暫無
暫無

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

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