Bạn có thể lấy đường dẫn đầy đủ dưới dạng một chuỗi, sau đó chia nó thành một danh sách bằng cách sử dụng ký tự phân cách trong hệ điều hành của bạn. Sau đó, bạn nhận được tên chương trình, tên thư mục, v.v. bằng cách truy cập các phần tử từ cuối danh sách bằng cách sử dụng các chỉ số âm.
Như thế này:
import os
strPath = os.path.realpath(__file__)
print( f"Full Path    :{strPath}" )
nmFolders = strPath.split( os.path.sep )
print( "List of Folders:", nmFolders )
print( f"Program Name :{nmFolders[-1]}" )
print( f"Folder Name  :{nmFolders[-2]}" )
print( f"Folder Parent:{nmFolders[-3]}" )
Kết quả của phần trên là:
Full Path    :C:\Users\terry\Documents\apps\environments\dev\app_02\app_02.py
List of Folders: ['C:', 'Users', 'terry', 'Documents', 'apps', 'environments', 'dev', 'app_02', 'app_02.py']
Program Name :app_02.py
Folder Name  :app_02
Folder Parent:dev