Django的文件夾結(jié)構(gòu) projectName/websiteName/appName
manage.py 所在路徑為:D:/projectA/website1/manage.py
views.py 所在路徑為:D:/projectA/website1/app1/views.py
D:/projectA/website1/app1/module1.py
如果要引用自定義模塊,引用自定義的模塊?
from .A import AAA? ? (在 if __name__ == "__main__" 中會報錯)
from A import AAA? ? (在網(wǎng)頁執(zhí)行中會報錯)
from?websiteName.appName.moduleA?import?some_function
要在view.py中使用相對路徑讀取文件 D:/projectA/website1/app1/abc.txt
如果使用?with open("abc.txt", 'r') as f??會報錯 FileNotFoundError: [Errno 2] No such file or directory?
因為相對路徑是相對于當(dāng)前工作目錄而言,而不是相對于views.py
所在的目錄。
解決方案
?要實現(xiàn)相對于views.py文件的相對路徑來讀取abc.txt,推薦使用Django提供的BASE_DIR
設(shè)置來構(gòu)建路徑 。
from django.conf import settings
def get_config():
base_dir = settings.BASE_DIR
config_file_path = os.path.join(base_dir, 'app1', 'myconfig.txt')
with open(config_file_path, 'r') as config_file:
config_data = config_file.read()
return config_data
當(dāng)在 if __name__ == "__main__":
塊內(nèi)使用相對導(dǎo)入時,容易犯的錯誤之一是與模塊結(jié)構(gòu)相關(guān)的錯誤。下面是一個示例,演示了在這種情況下可能發(fā)生的問題:文章來源:http://www.zghlxwxcb.cn/news/detail-701645.html
mypackage/
__init__.py
main.py
subpackage/
__init__.py
moduleA.py
moduleB.py
這種情況下,建議使用絕對路徑導(dǎo)入文章來源地址http://www.zghlxwxcb.cn/news/detail-701645.html
到了這里,關(guān)于Django 用相對路徑方式引用自定義模塊 或 文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!