2016-07-12 44 views
0

我寫了一個函數,可以找到路徑中的所有version.php文件。我正在嘗試使用該函數的輸出並從該文件中找到一行。那找到該文件的功能是:查找文件,然後在這些文件中找到一個字符串

def find_file(): 
    for root, folders, files in os.walk(acctPath): 
    for file in files: 
     if file == 'version.php': 
     print os.path.join(root,file) 
find_file() 

有路徑的幾個version.php文件,我想從每個這些文件返回一個字符串。

編輯: 謝謝你的建議,我的代碼實現不符合我的需要。我能夠通過創建一個列表並將每個項目傳遞給第二部分來弄清楚。這可能不是最好的方法,我只做了幾天的Python。

def cmsoutput(): 
    fileList = [] 
    for root, folders, files in os.walk(acctPath): 
    for file in files: 
     if file == 'version.php': 
     fileList.append(os.path.join(root,file)) 

    for path in fileList: 
    with open(path) as f: 
     for line in f: 
     if line.startswith("$wp_version ="): 
      version_number = line[15:20] 
      inst_path = re.sub('wp-includes/version.php', '', path) 
      version_number = re.sub('\';', '', version_number) 
      print inst_path + " = " + version_number 

cmsoutput() 
+0

你想返回哪個字符串?基於什麼標準? –

+0

我正在尋找的字符串是「$ wp_version =」,除了它的存在以外,沒有其他標準。 – cthulhuplus

回答

0

既然你想使用你的函數的輸出,你必須要return東西。打印它不會削減它。假設一切正常,它具有如下稍微修改:

import os 


def find_file(): 
    for root, folders, files in os.walk(acctPath): 
     for file in files: 
      if file == 'version.php': 
       return os.path.join(root,file) 

foundfile = find_file() 

現在變量foundfile包含我們要看看文件的路徑。尋找文件中的字符串,然後可以做像這樣:

with open(foundfile, 'r') as f: 
    content = f.readlines() 
    for lines in content: 
     if '$wp_version =' in lines: 
      print(lines) 

還是在功能版本:

def find_in_file(string_to_find, file_to_search): 
    with open(file_to_search, 'r') as f: 
     content = f.readlines() 
     for lines in content: 
      if string_to_find in lines: 
       return lines 

# which you can call it like this: 
find_in_file("$wp_version =", find_file()) 

注意代碼的功能版本,因爲它找到一個以上將盡快終止您正在尋找的字符串的實例。如果你想得到他們全部,它必須被修改。

相關問題