How do I use several files in python?

-2

I'm doing a program, and I have a file, which is the main part of the program. What happens is that I have a snippet code for the credits and I would like to put it in another file so as not to have a single very long file, since the snippet has a length considerable. Tell me how to please

    
asked by Gabriel Mation 20.10.2018 в 22:52
source

1 answer

1

You can import other files from the same directory with import . For example, given the following directory:

src/
├── main.py
└── snippets.py

snippets.py:

 A = 2

main.py:

import snippets
print snippets.A
# 2

You can also import only part of snippets with from/import

main.py:

from snippets import A
print A
# 2

Keep in mind that for larger projects, where you have several folders, you should also add a __init__.py file to each folder of the project code, so that python knows that it should treat that folder as a code package. To access another directory you must use the route with the import.

src/
├── snippets/
│   ├── snippet1.py
│   ├── snippet2.py
│   └── __init__.py
├── main.py
└── __init__.py

snippet1.py:

 A = 2

main.py:

from snippets import snippet1
print snippet1.A
# 2

Or:

main.py:

from snippets.snippet1 import A
print A
# 2
    
answered by 21.10.2018 / 01:25
source