I have a python project that's structured somewhat like this
Project/
src/
main.py
include.py
trace.py
doc/
readme.txt
lib/
trace/
treetrace.txt
datatrace.txt
and inside trace.py I have code that is supposed to write to files in Project/trace/ using
with open("path-to-Projects/trace/somefile.txt") as outfile:
outfile.write("some-trace-data")
I want to make it so that if someone were to run trace.py from Project/ or from Project/src/ or any directory within this structure, trace.py knows the path to Project/trace/ so that trace files don't get written to the wrong directory. Is this possible?
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)
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).trace_filename contains the path to the file you are looking for.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With