4

Preferably without the entire directory address. Can I define the folder relative to my executable script's position?

dataframe.to_csv('findorb_data.txt',header=False, index=False)
M. Hill
  • 41
  • 1
  • 2
  • 1
    I think this is basically a repeat of this [question](https://stackoverflow.com/questions/35384358/how-to-open-my-files-in-data-folder-with-pandas-using-relative-path)? – Stev Feb 12 '18 at 11:29
  • Possible duplicate of [How to open my files in \`data\_folder\` with pandas using relative path?](https://stackoverflow.com/questions/35384358/how-to-open-my-files-in-data-folder-with-pandas-using-relative-path) – Kasia Gogolek Feb 12 '18 at 11:53

2 Answers2

5

You can use the __file__ variable that contains the full path to the script. So, something like this:

import os
file_dir = os.path.dirname(os.path.abspath(__file__))
csv_folder = 'csv files'
file_path = os.path.join(file_dir, csv_folder, 'findorb_data.txt')
dataframe.to_csv(file_path, header=False, index=False)
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
Evgenii
  • 335
  • 2
  • 11
2

You can always use relative path syntax but you can also use something like this to find the parent directory of your script.

import os
import sys
script_dir = os.path.abspath(os.path.dirname(sys.argv[0]) or '.')

So if your csv is in the folder `../csv_dir/csv.csv' you can use

csv_path = os.path.join(script_dir, '../csv_dir/csv.csv')
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47