I believe your goal is to write to a file whose position is relative to your script. In Python, the path to your script is in the variable __file__
. From there, you subtract the file name part, then append ../trace/filename.txt. Here is how I do it:
import os
# Get the directory in which this script resides
script_path = os.path.split(__file__)[0]
# Trace file's location is relative to the script
trace_filename = os.path.join(script_path, '..', 'trace', 'out.txt')
print 'Trace file is at: {}'.format(trace_filename)
Discussion
- the
os.path.split()
function splits the path name of the script into pieces: the path and the file name. I am only interested in the path (index 0). - After this block of code,
trace_filename
contains the path to the file you are looking for.