Share python get file name from path

phuocnhanmodel

New member
### Cách lấy tên tệp từ đường dẫn trong Python

Trong Python, bạn có thể lấy tên tệp từ một đường dẫn bằng hàm `os.path.basename ()`.Hàm này lấy một đường dẫn làm đối số của nó và trả về phần cuối của đường dẫn, đó là tên tệp.Ví dụ: nếu đường dẫn là `" /home/user/document/file.txt "`, `os.path.basename ()` Hàm sẽ trả về `" file.txt "`.

Dưới đây là một ví dụ về cách sử dụng hàm `os.path.basename ()` để lấy tên tệp từ một đường dẫn trong Python:

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

path = "/home/user/document/file.txt"

Tên tệp = OS.Path.Basename (Path)

in (tên tệp)
`` `

Mã này sẽ in đầu ra sau:

`` `
FILE.TXT
`` `

### Tài nguyên bổ sung

* [Tài liệu Python: Os.Path.Basename ()] (https://docs.python.org/3/l Library/os.path.html#os.path.basename)
* [Stack Overflow: Làm thế nào để lấy tên tệp từ một đường dẫn trong Python?]-Python)

### hashtags

* #Python
* #quản lý tệp
* #Đường dẫn
* #OS.Path
* #Basename
=======================================
### How to Get the File Name from a Path in Python

In Python, you can get the file name from a path using the `os.path.basename()` function. This function takes a path as its argument and returns the last part of the path, which is the file name. For example, if the path is `"/home/user/Documents/file.txt"`, the `os.path.basename()` function would return `"file.txt"`.

Here is an example of how to use the `os.path.basename()` function to get the file name from a path in Python:

```python
import os

path = "/home/user/Documents/file.txt"

filename = os.path.basename(path)

print(filename)
```

This code will print the following output:

```
file.txt
```

### Additional Resources

* [Python Documentation: os.path.basename()](https://docs.python.org/3/library/os.path.html#os.path.basename)
* [Stack Overflow: How to get the file name from a path in Python?](https://stackoverflow.com/questions/180870/how-to-get-the-file-name-from-a-path-in-python)

### Hashtags

* #Python
* #file-management
* #Path-manipulation
* #OS.Path
* #Basename
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top