'Open a file in python from 2 directory back

I want to read a file from 2 folders back..

with open('../../test.txt', 'r') as file:
    lines = file.readlines()
    file.close()

I want to read from ../../ two folders back. but not work.. How i can do that ?



Solution 1:[1]

Opening files in python is relative to the current working directory. This means you would have to change cd to the directory where this python file is located.

If you want a more robust solution:

To be able to run this from any directory, there is a simple trick:

import os

PATH = os.path.join(os.path.dirname(__file__), '../../test.txt')
with open(PATH, 'r') as file:
    lines = file.readlines()
    file.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 annes