Use function from an external folder

0

I have the following situation:

  • Within Pasta1\ I have a file that is my main code

  • This file codigo_principal.py reads a file that is in a subfolder within Pasta1\

  • I also have another folder, Pasta2 , and inside it I have a code, teste.py

  • The file teste.py needs to use the function of the file codigo_principal.py that reads Sub_pasta1\arquivo.txt

Follow the structure of the folders:

Pasta1/
    Sub_pasta1/
        arquivo.txt
    codigo_principal.py
Pasta2/
    teste.py

The problem already arose when I needed to import this file from a different folder, I was able to work around this problem using the module imp

I can use all the features of codigo_principal.py , but the function that reads arquivo.txt does not work because it tries to fetch this file from Pasta2\SubPasta1\arquivo.txt .

EDIT: I'm using and need to use the relative path, I can not use the absolute

This is the code I'm using in teste.py

import imp

wtf=imp.load_source("codigo_principal", "../Pasta1/codigo_principal.py")
wtf.funcao_le_arquivo()

But this way I get the error message:

  

FileNotFoundError: [Errno 2] No such file or directory: Sub_folder1 / file.txt

    
asked by anonymous 26.06.2017 / 01:09

1 answer

2

Just turn folder1 into a python package by placing an empty file with the name __init__.py , from there just import the functions you want from that package.

Example with Hello World:

Create a folder named project, inside it create folder1 and folder2, inside folder1, create an empty file with the name __init__.py so that this folder becomes a "package" and in that folder create the folder code. In the folder2 create the test file that will call the function of the main code. See below the figure of the folder structure and then the code.

project / folder1 / main_code.py

def hello():
    print ('Hello World')

project / folder2 / test.py

from pasta1.main_code import hello

hello()

Output:

Hello World

Process finished with exit code 0
    
26.06.2017 / 12:30