Reason for not being able to import (Importerror:no module named * * * * * * *)

Source: Internet
Author: User

In Python, each py file is called a module, and each directory with a __init__.py file is called a package. As long as the module or the directory in which the package resides is in Sys.path, you can use the Import module or the import package.

If you want to use code that is not in the current module, you need to use import, as we all know.

If you want to use the module (PY file) and the current module in the same directory, just import the corresponding file name, such as the use of b.py in a.py:

Import b

But what if you want to import a file of a different directory (for example, b.py)?

You first need to use the Sys.path.append method to add the directory where b.py resides in the search directory. Then import them, for example

Import Sys

Sys.path.append (' c:\xxxx\b.py ')

In most cases, the above code works very well. But if you don't see any problem with the code above, it's important to note that the code above sometimes finds no module or package (Importerror:no module named XXXXXX), because:

The SYS module is written in C, so the string supports ' \ n ', ' \ R ', ' \ t ', and so on to represent special characters. So the above code is best written as:

Sys.path.append (' c:\\xxx\\b.py ')

or Sys.path.append (' c:/xxxx/b.py ')

This avoids invalid search directory (Sys.path) settings because of the incorrect composition of the escape character.

Reason for not being able to import (Importerror:no module named * * * * * * *)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.