深度阅读

How to get filename from a path in Python

作者
作者
2023年08月22日
更新时间
8.0 分钟
阅读时间
0
阅读量

To get the filename from a path in Python, you can use the os.path.basename() function. Here’s an example:

import os

path = '/path/to/my/file.txt'
filename = os.path.basename(path)
print(filename)

In this example, we import the os module and define a path string (path) pointing to a file. We then use the os.path.basename() function to extract the filename from the path and store it in a new variable (filename). Finally, we print out the filename using the print() function.

Note that if the path points to a directory rather than a file, os.path.basename() will return the name of the directory, not the parent directory.

In general, you can use os.path.basename() to extract the filename from any path string, regardless of the operating system or path format.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。