-2

I've written a script that basically creates two new folders when it's run the first time, if the folders don't already exist.

import os

try:
    os.makedirs('results/graphs')

except OSError:
    pass

And everytime the script is run, the graphs are produced in the results/graphs folder.

But I noticed recently that if the script is run from another directory, (eg. script is in home/user/script/ but I run it from: home/user/programs/), the new folders are created in home/user/programs/.

My goal is ultimately that the folders are created only in the script folder and all eventual graphs that are produced will thus be destined to home/user/script/results/graphs.

Is there someway to achieve this using python?

I'm using Debian 8 and python 2.7.13. The graphs are produced using matplotlib.

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
AltoBalto
  • 371
  • 1
  • 7
  • 14
  • Take a look at this question: http://stackoverflow.com/questions/918154/relative-paths-in-python – Szabolcs Feb 27 '17 at 13:20
  • 1
    Possible duplicate of [How to reliably open a file in the same directory as a Python script](http://stackoverflow.com/questions/4060221/how-to-reliably-open-a-file-in-the-same-directory-as-a-python-script) – Jacques Gaudin Feb 27 '17 at 13:21
  • Did you try `sys.path[0]` to get the location of the script? – Christian W. Feb 27 '17 at 13:21

5 Answers5

2

It's a solution for me, check it (I tried it on windows):

import os
d = os.path.dirname(__file__) # directory of script
p = r'{}/results/graphs'.format(d) # path to be created

try:
    os.makedirs(p)
except OSError:
    pass
Szabolcs
  • 3,990
  • 18
  • 38
0

In your script results/graphs refers to the results folder within whatever folder you ran the script from. If you always want the folders to be created in /home/user/script/results/graphs use ~/script/results/graphs in your script instead. Alternatively you could hard code the whole path, /home/user/script/results/graphs.

Jeremy Farrell
  • 1,481
  • 14
  • 16
0

There is another way, apart from hard coding which is mentioned earlier. You can use __file__ to extract the path of the file where the script is present. And then you can use it to append as parent path to results/graphs

Arghya Saha
  • 5,599
  • 4
  • 26
  • 48
0

All you have to do is to define the path where your script is. This can be done within the code as:

path = 'home/user/script/'

or by getting the input from the user using a filedialog box.

Then you can use the path variable to make the directories.

os.makedirs(path + 'results/graphs')
joseph praful
  • 171
  • 1
  • 16
-1
##creating folder
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()

dirctry = os.path.dirname(file_path)
toolSharePath = os.path.abspath(dirctry)
final_directory = os.path.join(toolSharePath, r'new_folder')
if not os.path.exists(final_directory):
   os.makedirs(final_directory,exist_ok=True)