简体   繁体   中英

Python Skipping 'for' loop

I'm making a program that searches a file for code snippets. However, in my search procedure, it skips the for loop entirely (inside the search_file procedure). I have looked through my code and have been unable to find a reason. Python seems to just skip all of the code inside the for loop.

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

In Python, arguments are not passed by reference. That is, if you pass in an argument and the function changes that argument (not to be confused with data of that argument), the variable passed in will not be changed.

You're giving load_file an empty string, and that argument is referenced within the function as dest . You do assign dest , but that just assigns the local variable; it does not change f . If you want load_file to return something, you'll have to explicitly return it.

Since f was never changed from an empty string, an empty string is passed to search_file . Looping over a string will loop over the characters, but there are no characters in an empty string, so it does not execute the body of the loop.

Inside each function add global f then f would be treated as a global variable. You don't have to pass f into the functions either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM