Hướng dẫn python import file from another directory - tệp nhập python từ một thư mục khác

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:

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::

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:

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:

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


Làm cách nào để nhập tệp từ thư mục này sang thư mục khác trong Python?

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 .

Có thể nhập từ một tệp python khác?

Nếu bạn có các tệp Python của riêng bạn mà bạn muốn nhập, bạn có thể sử dụng câu lệnh nhập như sau: >>> Nhập My_File # Giả sử bạn có tệp, my_file.py trong thư mục hiện tại.# Đối với các tệp trong các thư mục khác, cung cấp đường dẫn đến tệp đó, tuyệt đối hoặc tương đối.use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.

Tôi có thể nhập một thư mục trong Python không?

Theo mặc định, bạn không thể.Khi nhập tệp, Python chỉ tìm kiếm thư mục mà tập lệnh điểm nhập đang chạy và SYS.. When importing a file, Python only searches the directory that the entry-point script is running from and sys.

Làm thế nào để bạn nhập một tệp vào Python?

Các bước để nhập tệp CSV vào Python bằng Pandas..
Bước 1: Chụp đường dẫn tệp.Đầu tiên, chụp toàn bộ đường dẫn nơi tệp CSV của bạn được lưu trữ.....
Bước 2: Áp dụng mã Python.....
Bước 3: Chạy mã.....
Bước tùy chọn: Chọn tập hợp con của các cột ..

Bài Viết Liên Quan

Chủ Đề