We help IT Professionals succeed at work.

how do I use python functions in a separate .py file?

2,413 Views
Last Modified: 2014-08-27
Greetings,
I'm writing a python script for someone as my first attempt in learning python.

The script is getting long, and I want to include functions.
But instead of putting all the functions in the front of the same file, I was wondering if there was a way to put it in a different file and refer to that function from the main .py file.

Thanks much.
Comment
Watch Question

CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Evan CutlerVolunteer Chief Information Officer

Author

Commented:
awesome.  If the import(?) is not in the same folder as the main.py file....do I import folder/name?
THanks
CERTIFIED EXPERT

Commented:
No. The import is more abstract (see https://docs.python.org/3/reference/simple_stmts.html#the-import-statement for various forms of the statement). Think about it similarly as about searching executables in OS using the PATH variable. Python has some rules where to search for the file of the name. Actually, there is the sys module that implements sys.path as list of directories where the modules are searched (see https://docs.python.org/3/library/sys.html#sys.path).

You can print the sys.path, and you can modify it if you need.

If you need to implement some hierarchy of modules, it is usually done via packages (https://docs.python.org/3/reference/import.html#regular-packages) that differ from a simple directory hierarchy. I suggest to read the doc or simply leave it out for now.
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Evan CutlerVolunteer Chief Information Officer

Author

Commented:
Thank you so much guys.
I have alot more questions, but that requires more points. ;)

Thanks again.
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.