[英]How to split and separate root directory and sub directories from the path in python
[英]How to get the path of a sub folder under root directory of the project in python?
不得不再次發布這個問題,因為我之前的問題已關閉,說我的問題沒有集中。 所以在這里我再試一次。
我的文件夾結構如下所示:
root_folder:
- core
- files
- solution
- sub_folder
- test.py
- tests
我需要從 python 文件test.py
中獲取子文件夾files
的絕對路徑。
嘗試了使用os.path.abs
和os.path.dirname
的各種方法,但對我不起作用。
任何幫助都將不勝感激。
測試代碼和output:
print(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'files'))
output: /home/kulasangar/Documents/bst_work/root_folder/solution/files
預期 output: /home/kulasangar/Documents/bst_work/root_folder/files
您可以使用sys.path
從代碼中的任何位置訪問項目的根目錄。
import sys
print('My nested folder : ', os.getcwd())
print('File name : ', os.path.basename(__file__))
print('Root path:', sys.path[1])
假設您發布的文件夾結構相同,我的項目文件夾名為testing
。 所以,output 是
My nested folder : /Users/hellbreak/Documents/Coding/Python Lab/testing/solutions/sub_folder
File name : test.py
Root path: /Users/hellbreak/Documents/Coding/Python Lab/testing
然后,如果您對特定路徑感興趣,您可以
print('My nested folder : ', os.getcwd())
print('File name : ', os.path.basename(__file__))
print('Root path:', sys.path[1]+'/files')
output:
My nested folder : /Users/hellbreak/Documents/Coding/Python Lab/testing/solutions/sub_folder
File name : test.py
Root path: /Users/hellbreak/Documents/Coding/Python Lab/testing/files
在@hellbreak 的回答之上,我想出了另一種方法:
from pathlib import Path
import os
current_dir = Path(__file__)
project_root_dir_path = [p for p in current_dir.parents if p.parts[-1] == 'root_folder'][0]
files_path = os.path.join(project_root_dir_path, 'files')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.