2017-05-16 39 views
1

目標:我正在嘗試查找特定文件名的絕對路徑。查找特定上層目錄的絕對路徑

場景:我的腳本在一些(great-grand-grand)-parent目錄中執行,而我的文件在某個地方(很好......) - 父目錄中。

問題:

E: 
├───Directory 
│ └───Sub Directory 
└───Grandparent Folder 
    ├───Parent Directory 
    │ └───script.py 
    └───Other Parent Directory 
     └───MyFile.txt 
  1. 偉大的,父目錄是越來越頻繁地搬來搬去。所以父目錄的絕對路徑是未知的。

  2. 該腳本在great-parent目錄中移動很多,並且在該目錄內更改文件級別,所以我不能只使用'../../..'來啓動父目錄。

  3. 我正在尋找的文件在great-parent目錄中移動很多。

一旦我擁有父目錄的絕對路徑,我可以在os.walk()左右找到我的文件。

嘗試:下面我有什麼工作,但我想象這是一個常見的問題,足以有一個內置的os命令,我不知道。

import os 

parent_folder = 'Grandparent Folder' 
search_file = 'MyFile.txt' 

# Get absolute path of grandparent directory. 
current_path = os.getcwd() 
parent_path = current_path.split(parent_folder)[0] + parent_folder 

# os.walk() from grandparent down until file is found. 
filepath= '' 
for root, dirs, files in os.walk(parent_path): 
    for file in files: 
     if file == search_file: 
      filepath = '\\'.join([root, file]) 
+0

當前工作目錄和腳本目錄不必相同。你想在什麼基礎上搜索? – tdelaney

+0

腳本目錄 –

+0

'os.getcwd()'返回工作目錄,使用'__file__'獲取腳本目錄。 –

回答

0

嘗試使用pythons glob模塊來查找路徑名。你可以找到官方文檔的詳細信息。這樣即使目錄移動,你也可以每次找到路徑。

+0

這是否幫助我找到我的祖父目錄,或者只是一旦我有父目錄的文件? –

+0

@MichaelMolter:你也可以使用fnmatch()和glob()的組合,並且只要知道腳本名稱或文件名(這些應該是唯一的,否則可能有多個匹配) –

+0

@MichaelMolter: 請參閱此SO問題 - http://stackoverflow.com/questions/14798220/how-can-i-search-sub-folders-using-glob-glob-module-in-python 一旦找到該文件,你可以返回工作目錄。 –