2013-01-12 117 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也传递到函数中。