Python: open txt file in different folder

0

I have the following hierarchy

> Project
>        App1
>               folder1
>                      main.py
>        App2
>               folder1
>               folder2
>                      file.txt

I want to open file.txt from main.py but by default the function "open ()" looks in the directory of the file and its subdirectories. How would I be able to read file.txt from main.py without having to move files?

    
asked by Emmanuel Moran 08.03.2018 в 18:11
source

2 answers

0

Finally I could do what I wanted, in the static folder create a tmp folder which would be left with 777 permissions, so they could be accessed anywhere.

It should be noted that as he used django with python, the use of

was complicated
with open("../../App2/folder2/file.txt", "r") as f:

so I started a variable in settings with the path to the files that would be modified by the views.py files of each django application.

file = open(settings.AJAX_FILES+"data.txt","w",encoding='utf-8')

The use of encoding does not have to do with the question, but I still leave it with a flaw that was presented to me to present the texts of the file.

    
answered by 12.03.2018 / 15:15
source
0

Just pass open as the first argument the relative route to the file from main.py , in your case it would be something like this:

with open("../../App2/folder2/file.txt", "r") as f:
    # Resto de código aquí

You just have to take into account the meaning of the points:

  • . ( dot ) refers to the current directory.
  • .. ( double dot ) allows us to reference the parent directory of the current one.

Therefore ../ places us in App1 and ../../ in Project .

    
answered by 08.03.2018 в 18:18