-1

If I write

current_path = os.path.dirname(os.path.abspath(__file__))

Then I get the path to the current file running.

What I need is the absolute path from the current file to:

'../Data/my_data.csv'

How do I use os to output the absolute path to '../Data/my_data.csv' without changing my working directory or anything else?

Chris
  • 28,822
  • 27
  • 83
  • 158
  • 1
    os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'Data/my_data.csv')) – Maximilian Peters Jan 30 '17 at 16:58
  • Possible duplicate of [Using Python's os.path, how do I go up one directory?](http://stackoverflow.com/questions/9856683/using-pythons-os-path-how-do-i-go-up-one-directory) – Maximilian Peters Jan 30 '17 at 16:59
  • Possible duplicate of [How to get an absolute file path in Python](http://stackoverflow.com/questions/51520/how-to-get-an-absolute-file-path-in-python) – Will Jan 30 '17 at 16:59

2 Answers2

2

You can use os.path.join:

current_path = os.path.dirname(os.path.abspath(__file__))
new_path = os.path.join(current_path, '..', 'Data', 'my_data.csv')
aldarel
  • 446
  • 2
  • 7
  • And how is this any different to using `os.path.abspath('../Data/my_data.csv')` directly? – wim Jan 30 '17 at 17:02
  • 1
    It will depend on if you are running the script from the directory with the file in it. – tmwilson26 Jan 30 '17 at 17:04
  • 1
    + it is more multiplatform solution. Python os module handles proper usage '\', '/' according to the system used. – aldarel Jan 30 '17 at 17:07
  • Good point, I don't use windows for my programming all that often, but have run into this issue so that is probably the best way to go for generality. – tmwilson26 Jan 30 '17 at 17:11
  • I've yet to encounter a platform where `/` doesn't work as a path separator. It works on Windows, Mac, Linux ... – wim Feb 01 '17 at 22:16
0

You could do something like

'{}/../Data/my_data.csv'.format(current_path)
tmwilson26
  • 741
  • 5
  • 17