Python Forum

Full Version: python library not defined in user defined function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Why doesn't this work?

def main():
    import os
    fileName = "text.txt"
    userfunction(fileName)

def userfunction(fileName):
    os.path.exists(fileName)

main()
I get the following error:
Error:
NameError: name 'os' is not defined
Because the import is local to your main function. Imports should go at the top of the file, as per PEP 8.
As mentioned above by ndc85430 you need to import your modules before the actual code functions are executed.

import os

def main():
    fileName = "text.txt"
    userfunction(fileName)

def userfunction(fileName):
    os.path.exists(fileName)

main()