Reputation: 11
The code I am using is shown here:
import os.path
def def1():
global filename
if os.path.isfile(filename+ ".txt") == True:
print ("Filename exists")
if os.path.isfile(filename+ ".txt") == False:
print("Filename dosent exist")
def def2():
global filename
filename = input("Please input the name if the file you want to see exists")
def Main():
def1()
def2()
Main()
What the code does is check whether or not a file exists, and the user can input the name of the file he/she wishes to check. This code will be used in a much bigger code file. I am not able to understand why I get this error when I run the code:
Traceback (most recent call last):
File "/Users/Sid/Desktop/existfiletest.py", line 18, in <module>
Main()
File "/Users/Sid/Desktop/existfiletest.py", line 15, in Main
def1()
File "/Users/Sid/Desktop/existfiletest.py", line 5, in def1
if os.path.isfile(filename+ ".txt") == True:
NameError: name 'filename' is not defined
I have defined the variable 'filename' as a global in def2(), but I start off the program by calling def1(). The variable 'filename' is a global, so I don't see why it can't be used in def1(). And also, if anyone says to call def2() first, yes that works. However I would like to know whether I can use a variable before defining it, as this is the case in my bigger code.
Thanks in advance.
Upvotes: 1
Views: 180
Reputation: 1366
Sort answer:
replace:
def Main():
def1()
def2()
by
def Main():
def2()
def1()
Your mistake is not the fact that you defined the global variable earlier in the file. But by calling def1
first, you have left the variable undefined. So you must call def2
first to initialize and give it a value.
Secondly you do not need to perform the if test twice:
def def1(filename):
if os.path.isfile(filename+ ".txt") == True:
print ("Filename exists")
else:
print("Filename does not exist")
Upvotes: 1
Reputation: 845
Save the filename in the main function and then pass it to the def1 function like so:
import os.path
def def1(filename):
if os.path.isfile(filename+ ".txt") == True:
print ("Filename exists")
if os.path.isfile(filename+ ".txt") == False:
print("Filename dosent exist")
def Main():
filename = input("Please input the name if the file you want to see exists")
def1(filename)
Main()
Upvotes: 0
Reputation: 12140
Don't use global variables. It is really bad practice. Use function arguments. You can change you code to:
import os.path
def def1(filename):
if os.path.isfile(filename+ ".txt") == True:
print ("Filename exists")
if os.path.isfile(filename+ ".txt") == False:
print("Filename dosent exist")
def def2():
return input("Please input the name if the file you want to see exists")
def Main():
filename = def2()
def1(filename)
Main()
And of course you can't use variable before defining it. But you can define it with some default value.
Upvotes: 0