2014-06-12 46 views
0

我有一個python文件來打印另一個文件的完整路徑,該文件可以在其他目錄之一中。我的文件夾結構如下:查找未知目錄中的文件的路徑

D:\Main\Script\Myscript.py 
D:\Main\Target\A\cow.txt 
D:\Main\Target\B\dog.txt,p1.txt 
D:\Main\Target\c\cat.txt 
D:\Main\Target\D\Q1.txt 

當我給出文件名時,我想打印該文件的完整路徑。例如,如果我給「Q1.txt」,它應該打印D:\Main\Target\D\Q1.txt。我嘗試了以下內容,讓我的輸入文件爲Myfile1

Scriptloc=os.path.join(os.path.dirname(__file__)) 
if (os.path.exist(Scriptloc+".."+os.sep+".."+os.sep+A+Myfile1)): 
    print "Filepath is "+Scriptloc+".."+os.sep+".."+os.sep+A+Myfile1 
elif (os.path.exist(Scriptloc+".."+os.sep+".."+os.sep+A+Myfile1)): 
    print "Filepath is "+Scriptloc+".."+os.sep+".."+os.sep+B+Myfile1 
elif (os.path.exist(Scriptloc+".."+os.sep+".."+os.sep+C+Myfile1)): 
    print "Filepath is "+Scriptloc+".."+os.sep+".."+os.sep+C+Myfile1 
elif (os.path.exist(Scriptloc+".."+os.sep+".."+os.sep+D+Myfile1)): 
    print "Filepath is "+Scriptloc+".."+os.sep+".."+os.sep+C+Myfile1 
else: 
    print "File not found" 

有沒有其他簡單的方法來做到這一點?

+1

如果有名爲'Q1.txt'幾個文件? – bereal

+0

什麼是''''? –

+0

'.. \'將給父目錄 – TVSuser1654136

回答

2

你可以使用os.walk,例如:

def find_file(basedir, filename): 
    for dirname, dirs, files in os.walk(basedir): 
     if filename in files: 
      yield os.path.join(dirname, filename) 

for found in find_file(basedir, 'Q1.txt'): 
    print found 

這樣,你就不必硬編碼的文件夾結構。

1

你可以使用pox,它內置瀏覽目錄和文件系統與操作工作

>>> from pox.shutils import find 
>>> find('Q1.txt') 
['/Users/mmckerns/Main/Target/D/Q1.txt'] 

以上可以從任何目錄下運行,並且可以指定一個根目錄開始改變。它會找到所有文件名稱Q1.txt,並返回它們的完整路徑。有許多選項可以搜索目錄,並且可以忽略軟鏈接以及各種其他的東西。搜索是一種快速搜索,很像unix的find函數。如果失敗,pox.shutils.find將故障轉移到python的os.walk(慢得多)......如果您想要保持在標準庫中,無論出於何種原因,這都是您可以使用的。

得到pox這裏:https://github.com/uqfoundation