Reputation: 484
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
Upvotes: 0
Views: 284
Reputation: 9511
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.
Upvotes: 0
Reputation: 129119
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.
Upvotes: 2