0

I want to make a user made function library filled with custom functions to use in other codes without having to write all the code and just importing the file, i have defined a function called hello() which prints hello, however when i try to call it in my secondary file it say the hello() is not defined.

'python library.py'

def hello():
     print("Hello")

'library test.py'

myfile = open('python library.py', 'a')

hello()
  • you should use `import` to call functions from a different file. What you are doing here will just read/write to file – PYA Jul 05 '17 at 18:28
  • Because doing `open(<>)` just opens a file for reading/writing. This does not load your module at all. that is what the `import` statement is for. – juanpa.arrivillaga Jul 05 '17 at 18:31
  • Could you show me an example of using the import syntax –  Jul 05 '17 at 18:33

1 Answers1

0

The open() command is for opening a file as text to read from or write to (principally). Your 'a' is saying you want to append text to the file `'python library.py'

One option to do what you want is to use import to get your functions from the file.

from file import function

in your case

from python library import hello
#NOTE the .py is left off
hello()

If you have multiple functions to import, you can do import * instead of import function. Though I am not sure if this will work having a space in your filename, so if it gives an error, my first suggestion would be to rename your file using an underscore or something so that it's all one word.

More info: How to call a function from another file in Python?

Davy M
  • 1,697
  • 4
  • 20
  • 27