Share python get source directory

vinhtoanlethuc

New member
### Cách nhận thư mục nguồn trong Python

Hàm `os.path.dirname ()` Trả về thư mục của một đường dẫn đã cho.Điều này có thể được sử dụng để có được thư mục nguồn của tệp Python.Ví dụ: mã sau sẽ in thư mục nguồn của tệp hiện tại:

`` `Python
Nhập hệ điều hành

in (Os.Path.Dirname (__ File__))
`` `

Điều này sẽ in thư mục nơi đặt tệp hiện tại.Nếu tệp hiện tại được đặt trong thư mục `/home/user/urject/myProject`, đầu ra của mã sẽ là`/home/user/presject/myProject`.

Bạn cũng có thể sử dụng danh sách `sys.path` để lấy thư mục nguồn của tệp python.Danh sách `sys.path` chứa các thư mục mà Python tìm kiếm các mô -đun khi nhập chúng.Thư mục đầu tiên trong danh sách `sys.path` là thư mục làm việc hiện tại.Vì vậy, nếu thư mục làm việc hiện tại là thư mục `/home/user/presject/myProject`, thư mục nguồn của tệp hiện tại sẽ là mục đầu tiên trong danh sách` sys.path`.

`` `Python
nhập khẩu sys

in (sys.path [0])
`` `

Điều này sẽ in thư mục nơi đặt tệp hiện tại.Nếu tệp hiện tại được đặt trong thư mục `/home/user/urject/myProject`, đầu ra của mã sẽ là`/home/user/presject/myProject`.

### hashtags

* #Python
* #Programming
* #mã nguồn
* #Danh mục
* #tài liệu
=======================================
### How to Get Source Directory in Python

The `os.path.dirname()` function returns the directory of a given path. This can be used to get the source directory of a Python file. For example, the following code will print the source directory of the current file:

```python
import os

print(os.path.dirname(__file__))
```

This will print the directory where the current file is located. If the current file is located in the `/home/user/projects/myproject` directory, the output of the code will be `/home/user/projects/myproject`.

You can also use the `sys.path` list to get the source directory of a Python file. The `sys.path` list contains the directories that Python searches for modules when importing them. The first directory in the `sys.path` list is the current working directory. So, if the current working directory is the `/home/user/projects/myproject` directory, the source directory of the current file will be the first item in the `sys.path` list.

```python
import sys

print(sys.path[0])
```

This will print the directory where the current file is located. If the current file is located in the `/home/user/projects/myproject` directory, the output of the code will be `/home/user/projects/myproject`.

### Hashtags

* #Python
* #Programming
* #Source-code
* #directory
* #file
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top