Using an external folder function

Asked

Viewed 611 times

0

I have the following situation:

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

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

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

  • The archive teste.py need to use file function codigo_principal.py reading Sub_pasta1\arquivo.txt

Follows the folder structure:

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

The problem has already arisen when I needed to import this file from a different folder, I managed to get around this problem using the module imp

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

EDIT: I am using and need to use the relative path, I cannot use the absolute

This is the code I’m using on 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_pasta1/file.txt

  • Are you using the absolute path to open the file? If it is relative, the path is relative to the directory Pasta2, looking for Pasta2/Sub_pasta1/arquivo.txt.

  • I forgot to quote, I need to use the relative path

  • Then enter the path as a function parameter and in the file teste.py you set the path relative to Pasta2.

1 answer

3


Just turn the folder 1 into a python package by putting 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 called project, within it create the pasture1 and the pasture2, inside the pasture1, create an empty file with the name __init__.py for that folder to become a "package" and, in that same folder, create the main code. In the folder 2 create the test file that will call the main code function. See below the figure of the folder structure and then the code.

inserir a descrição da imagem aqui

project/pasta1/main_code.py

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

project/pasture2/test.py

from pasta1.main_code import hello

hello()

Output:

Hello World

Process finished with exit code 0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.