2011-03-01 58 views
9

我還是Python新手(使用2.6),我試圖在文件系統範圍內搜索文件只是文件名可用並返回窗口上的絕對路徑。我搜索並發現了一些像scriptutil.py這樣的模塊,並查看了os模塊,但沒有找到任何適合我需要的東西(或者我可能沒有正確理解所有東西,將它應用到我需要的東西上,因此沒有包含任何東西碼)。我將不勝感激任何幫助。Python:當只有文件名(不是路徑)可用時,如何對文件進行全系統搜索

謝謝。

回答

15

os.walk()函數是這樣做的一種方法。

import os 
from os.path import join 

lookfor = "python.exe" 
for root, dirs, files in os.walk('C:\\'): 
    print "searching", root 
    if lookfor in files: 
     print "found: %s" % join(root, lookfor) 
     break 
+1

@馬丁·斯通的確是這樣,但它需要一個路徑,或者是隻搜索當前工作目錄(如果我理解正確的話) – ldmvcd

+0

@ldmvcd,它遞歸從你告訴它開始在目錄中搜索 –

+0

@Martin Stone ** break **應該被刪除,因爲在不同的目錄中可能有幾個同名的文件 – eyquem

4

你可以開始在目錄和遞歸走路看着每一級的文件目錄結構。當然,如果你想搜索整個系統,你需要爲每個驅動器調用它。

os.path.walk(rootdir,f,arg) 

有一個很好的回答類似的問題here和另外一個here

+0

感謝您的鏈接,他們是有幫助的,就像上面發佈的答案。 – ldmvcd

+0

使用'os.path.walk',需要3個參數,自從Python 2.3(並且完全在3.0中移除)贊成os.walk',它只需要1個參數(並且有3個可選參數)就被棄用了。 – ArtOfWarfare

0

會是這樣的工作?

import os 
import sys 
import magic 
import time 
import fnmatch 

class FileInfo(object): 

    def __init__(self, filepath): 
     self.depth = filepath.strip('/').count('/') 
     self.is_file = os.path.isfile(filepath) 
     self.is_dir = os.path.isdir(filepath) 
     self.is_link = os.path.islink(filepath) 
     self.size = os.path.getsize(filepath) 
     self.meta = magic.from_file(filepath).lower() 
     self.mime = magic.from_file(filepath, mime=True) 
     self.filepath = filepath 


    def match(self, exp): 
     return fnmatch.fnmatch(self.filepath, exp) 

    def readfile(self): 
     if self.is_file: 
      with open(self.filepath, 'r') as _file: 
       return _file.read() 

    def __str__(self): 
     return str(self.__dict__) 



def get_files(root): 

    for root, dirs, files in os.walk(root): 

     for directory in dirs: 
      for filename in directory: 
       filename = os.path.join(root, filename) 
       if os.path.isfile(filename) or os.path.isdir(filename): 
        yield FileInfo(filename) 

     for filename in files: 
      filename = os.path.join(root, filename) 
      if os.path.isfile(filename) or os.path.isdir(filename):    
       yield FileInfo(filename) 


for this in get_files('/home/ricky/Code/Python'): 
    if this.match('*.py'): 
     print this.filepath 
相關問題