2013-01-12 118 views
0

我正在製作一個程序來搜索文件中的代碼片段。但是,在我的搜索過程中,它完全跳過了for循環(在search_file過程中)。我查看了我的代碼,一直無法找到原因。 Python似乎只是跳過for循環中的所有代碼。Python跳過'for'循環

import linecache 

def load_file(name,mode,dest): 
    try: 
     f = open(name,mode) 
    except IOError: 
     pass 
    else: 
     dest = open(name,mode) 

def search_file(f,title,keyword,dest): 
    found_dots = False 

    dest.append("") 
    dest.append("") 
    dest.append("") 

    print "hi" 

    for line in f: 
     print line 
     if line == "..":    
      if found_dots: 
       print "Done!" 
       found_dots = False 
      else: 
       print "Found dots!" 
       found_dots = True  
     elif found_dots: 
      if line[0:5] == "title=" and line [6:] == title: 
       dest[0] = line[6:] 
      elif line[0:5] == "keywd=" and line [6:] == keyword: 
       dest[1] = line[6:] 
      else: 
       dest[2] += line 

f = "" 
load_file("snippets.txt",'r',f) 
search = [] 
search_file(f,"Open File","file",search) 
print search 

回答

2

在Python中,參數不是通過引用傳遞的。也就是說,如果你傳入一個參數並且函數改變那個參數(不要與的數據那個參數混淆),那麼通過傳遞的變量不會被改變。

您正在給load_file一個空字符串,並且該參數在函數中被引用爲dest。你確實分配了dest,但這只是分配了局部變量;它不會改變f。如果你想load_file返回的東西,你必須明確return它。

由於f從未從空字符串中更改,所以將空字符串傳遞給search_file。在一個字符串上循環會遍歷字符,但空字符串中沒有字符,因此它不會執行循環的主體。

0

在每個函數中添加global f然後f將被視爲全局變量。您不必將f也傳遞到函數中。