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_filean empty string, and that argument is referenced within the function asdest. You do assigndest, but that just assigns the local variable; it does not changef. If you wantload_fileto return something, you’ll have to explicitlyreturnit.Since
fwas never changed from an empty string, an empty string is passed tosearch_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.