سؤال

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)

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.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top