M. Hill
M. Hill

Reputation: 51

Using pandas, how do I save an exported csv file to a folder relative to the scripts position?

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)

Upvotes: 5

Views: 8394

Answers (2)

Zhenya K.
Zhenya K.

Reputation: 345

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)

Upvotes: 5

FHTMitchell
FHTMitchell

Reputation: 12157

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')

Upvotes: 2

Related Questions