क्योंकि sys.path
सूची में पहली निर्देशिका में शुरू होने वाले अनुक्रमिक क्रम में निर्देशिका में पाइथन चेक करता है, जब तक कि यह .py
फ़ाइल ढूंढता है, तब तक यह खोज नहीं रहा।
आदर्श रूप से, वर्तमान निर्देशिका या स्क्रिप्ट की निर्देशिका सूची में पहली बार पहला तत्व है, जब तक कि आप इसे संशोधित न करें, जैसा आपने किया था। documentation से -
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.
तो, सबसे शायद, आप मॉड्यूल आप से आयात करने की कोशिश कर रहे थे के रूप में एक ही नाम के साथ एक .py
फ़ाइल वर्तमान निर्देशिका (जहाँ स्क्रिप्ट से चलाया जा रहा था) में हुआ था।
ही, ध्यान दें करने के लिए ImportError
के बारे में एक बात यह है कि, मान लीजिए कि आयात त्रुटि कहते हैं - ImportError: No module named main
- यह मतलब नहीं है main.py
ओवरराइट है, कोई अगर उस ओवरराइट किया गया हम इसे पढ़ने का प्रयास मुद्दों कर नहीं किया जाएगा। इसके ऊपर कुछ मॉड्यूल जो एक के साथ अधिलेखित हो गया है। py
या कुछ अन्य फ़ाइल।
उदाहरण -
मेरे निर्देशिका संरचना लगता है कि -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
अब testmain.py
से, मैं from shared import phtest
कहते हैं, यह ठीक काम करता है।
अब कहते हैं कि मैं एक shared.py test
directory` में, उदाहरण के परिचय की सुविधा देता है - जब मैं testmain.py
से from shared import phtest
करने की कोशिश
- test
- shared
- __init__.py
- phtest.py
- testmain.py
- shared.py
अब, मैं त्रुटि प्राप्त होगी -
ImportError: cannot import name 'phtest'
जैसा कि आप ऊपर देख सकते हैं, समस्या उत्पन्न करने वाली फ़ाइल shared.py
है, phtest.py
नहीं है।
संभावित डुप्लिकेट [sys.path.insert (पथ, पथ) के बजाय sys.path.append (पथ) का उपयोग क्यों करें?] (Http://stackoverflow.com/questions/10095037/why-use-sys- पथ-एपेंडपैथ-इसके-सीएस-पथ-सम्मिलित 1-पथ) – CrandellWS