Hướng dẫn how do i import a directory in python? - làm cách nào để nhập một thư mục trong python?

Trong Python 3.4 trở lên, bạn có thể nhập trực tiếp từ tệp nguồn (liên kết đến tài liệu). Đây không phải là giải pháp đơn giản nhất, nhưng tôi bao gồm câu trả lời này cho sự hoàn chỉnh.

Đây là một ví dụ. Đầu tiên, tệp được nhập, được đặt tên là foo.py:

def announce():
    print("Imported!")

Mã nhập tệp ở trên, được truyền cảm hứng rất nhiều bởi ví dụ trong tài liệu:

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()

Đầu ra:


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

Lưu ý rằng tên biến, tên mô -đun và tên tệp không cần phải khớp. Mã này vẫn hoạt động:

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()

Đầu ra:


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

Lưu ý rằng tên biến, tên mô -đun và tên tệp không cần phải khớp. Mã này vẫn hoạt động:

Trong khi làm việc trên các dự án lớn, chúng tôi có thể đối mặt với một tình huống mà chúng tôi muốn nhập một mô -đun từ một thư mục khác. Nhưng vì một số lý do, mô -đun có thể không được nhập chính xác. Bây giờ đừng lo lắng nếu mô -đun của bạn không được nhập chính xác. Trong bài viết này, chúng tôi sẽ thảo luận về các cách để nhập một mô -đun từ một thư mục khác. & NBSP;module from a different directory. But for some reason, the module may not be imported correctly. Now don’t worry if your module is not imported correctly. In this article, we will discuss ways to import a module from another directory. 

Lưu ý: Một mô -đun chỉ là một chương trình Python kết thúc bằng phần mở rộng .py và một thư mục chứa một mô -đun trở thành một gói.A module is just a Python program that ends with .py extension and a folder that contains a module becomes a package.

Cấu trúc thư mục:

 - Folder_1
    - main.py
 - Folder_2
     - module1.py

Hãy giả sử, để nhập cách nhập tệp trong Python, chúng tôi có hai thư mục khác nhau, một có chứa Main.py là tệp Python chính của chúng tôi nơi chúng tôi muốn nhập Module1 từ thư mục_2. & NBSP;

MODULE1: Chứa hai hàm gọi là Thêm và ODD_EVEN. Chức năng Thêm sẽ có hai đối số và trả về việc bổ sung chúng. Hàm ODD_EVEN sẽ chỉ lấy một đối số và in ngay cả khi số chẵn hoặc in lẻ nếu số là lẻ. contains two functions called add and odd_even. The function add will takes two arguments and return the addition of them. The odd_even function will take only one argument and print Even if the number is even or print Odd if the number is odd.

module1.py 

Python3

def add(a, b):

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()
0____11
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()
2
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()
3
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()
4

def

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()
6

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()
0
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()
8
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()
9

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
0

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
6

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
8

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
9
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
0

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()
0
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
2

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
5


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
6

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
8
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
7
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
0

Nếu chúng ta chỉ cần cố gắng nhập Module1 từ thư mục_2, chúng ta sẽ gặp phải lỗi sau.module1 from Folder_2, we will be encountering the following error.

main.py

Python3

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
9

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
0


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
2
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
0

Output:

Hướng dẫn how do i import a directory in python? - làm cách nào để nhập một thư mục trong python?

Lỗi

ModulenotFounderRor, bởi vì theo mặc định, trình thông dịch Python sẽ chỉ kiểm tra tệp trong thư mục hiện tại và chúng tôi cần đặt đường dẫn tệp theo cách thủ công để nhập các mô -đun từ một thư mục khác. Chúng ta có thể làm điều này bằng cách sử dụng nhiều cách khác nhau. Những cách này được thảo luận dưới đây chi tiết., because by default Python interpreter will check for the file in the current directory only, and we need to set the file path manually to import the modules from another directory. We can do this using various ways. These ways are discussed below in detail.

Phương pháp 1: Nhập mô -đun từ các thư mục khác nhau bằng mô -đun SYS

Chúng ta có thể sử dụng sys.path để thêm đường dẫn của thư mục mới (thư mục từ nơi chúng ta muốn nhập các mô -đun) vào đường dẫn hệ thống để Python cũng có thể tìm mô -đun trong thư mục đó nếu nó không tìm thấy mô -đun trong thư mục hiện tại của nó. Khi sys.Path thuộc lớp loại danh sách để, chúng ta có thể dễ dàng sử dụng phương thức chèn để thêm đường dẫn thư mục.sys.pathto add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn’t find the module in its current directory. As sys.path falls under the list type class so, we can easily use the insert method to add the folder path.

Python3


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
5
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
9

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
9

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
9

 - Folder_1
    - main.py
 - Folder_2
     - module1.py
0

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4
 - Folder_1
    - main.py
 - Folder_2
     - module1.py
2
 - Folder_1
    - main.py
 - Folder_2
     - module1.py
3
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
0

 - Folder_1
    - main.py
 - Folder_2
     - module1.py
5

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
2
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
0


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
8
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
0
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
1

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1
 - Folder_1
    - main.py
 - Folder_2
     - module1.py
2

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
5

Output::

Hướng dẫn how do i import a directory in python? - làm cách nào để nhập một thư mục trong python?

Sử dụng SYS

Phương pháp 2: Sử dụng biến PythonPathEnv môi trường environment variable

Tương tự, nếu bạn không muốn sử dụng mô -đun SYS để đặt đường dẫn của thư mục mới. Bạn có thể gán một đường dẫn thư mục cho biến PythonPath và vẫn giúp chương trình của bạn hoạt động. & NBSP;sys module to set the path of the new directory. You can assign a directory path to the PYTHONPATH variable and still get your program working. 

Trong Linux, chúng ta có thể sử dụng lệnh sau trong thiết bị đầu cuối để đặt đường dẫn:

Xuất pythonpath = đường dẫn/đến/thư mục

Trong hệ thống Windows:

Đặt pythonpath = đường dẫn/đến/thư mục trực tuyến

Để xem liệu biến PythonPath có giữ đường dẫn của thư mục mới hay không, chúng ta có thể sử dụng lệnh sau:

Echo $ Pythonpath

Python3


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
5
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
9

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7

 - Folder_1
    - main.py
 - Folder_2
     - module1.py
5

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
2
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
0


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
8
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
0
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
1

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1
 - Folder_1
    - main.py
 - Folder_2
     - module1.py
2

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
5

Output:

Hướng dẫn how do i import a directory in python? - làm cách nào để nhập một thư mục trong python?

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
9

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
9

Sử dụng SYS

- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py

Phương pháp 2: Sử dụng biến PythonPathEnv môi trường new.py module from Folder_2 to our project’s Folder_1 main.py file.

Syntax:

Tương tự, nếu bạn không muốn sử dụng mô -đun SYS để đặt đường dẫn của thư mục mới. Bạn có thể gán một đường dẫn thư mục cho biến PythonPath và vẫn giúp chương trình của bạn hoạt động. & NBSP;

Python3

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
9

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
9

 - Folder_1
    - main.py
 - Folder_2
     - module1.py
0

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4
 - Folder_1
    - main.py
 - Folder_2
     - module1.py
2def6
import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
0

Sử dụng SYS

add(a, b):2

Output:

Hướng dẫn how do i import a directory in python? - làm cách nào để nhập một thư mục trong python?

Phương pháp 2: Sử dụng biến PythonPathEnv môi trường


Bạn có thể nhập một thư mục trong Python không?

Cách pythonic nhất để nhập một mô -đun từ một thư mục khác là đặt một tệp trống có tên __init__.py vào thư mục đó và sử dụng đường dẫn tương đối với ký hiệu dấu chấm. Ví dụ: một mô -đun trong thư mục chính sẽ được nhập từ .. Nhập mô -đun.place an empty file named __init__.py into that folder and use the relative path with the dot notation. For example, a module in the parent folder would be imported with from .. import module .

Làm cách nào để nhập một đường dẫn Python?

Chức năng nối ().Đây là cách dễ nhất để nhập mô -đun Python bằng cách thêm đường dẫn mô -đun vào biến đường dẫn.Biến đường dẫn chứa các thư mục thông dịch viên Python tìm kiếm để tìm các mô -đun được nhập trong các tệp nguồn.. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.

Làm cách nào để nhập một mô -đun cục bộ trong Python?

Làm thế nào để nhập các mô -đun cục bộ với Python..
Definitions..
Example..
Giải pháp đầu tiên: Thêm gốc vào sys.path ..
Nhập khẩu tương đối ..
Giải pháp thứ 2: Chạy như một mô -đun ..
Chạy như một mô -đun trên mã trực quan ..
Giải pháp thứ 3: Sửa đổi Pythonpath ..
Giải pháp 4RD (lỗi thời): Cài đặt ở chế độ có thể chỉnh sửa ..

Làm thế nào để tôi đưa ra một con đường đến một thư mục trong Python?

Để có được thư mục làm việc hiện tại trong Python, hãy sử dụng phương thức Os.getCwd ().Hàm này của mô -đun HĐH Python trả về chuỗi chứa đường dẫn tuyệt đối đến thư mục làm việc hiện tại.use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.