FaCoffee
FaCoffee

Reputation: 7909

Setting a working folder to where my script lives in Python

I was looking for an easy way to set a working folder at the beginning of my script to avoid having to change it each time I run my script from another machine. Sorry if it is silly but I can't find an answer without having to dive deeply into the sea of weird functions - and I don't know how to swim.

I would use it to save all images to the same specific folder.

My take:

#import stuff
filepath=raw_input('Provide the working directory: ')
#do stuff
plt.savefig(filepath+'\\image.jpg', dpi=2000,bbox='tight')

EDIT I have a number of files to save in one specific directory, the same where my script lives. But it is specified like this: C:\\Users\\User\\Desktop\\N_Scripts and it is on my own pc, but I oftentimes work on a different machine. How to preset the directory where all my images go to at the beginning of my script with something like raw_input?

Thank you for your help!

Upvotes: 0

Views: 72

Answers (1)

jfs
jfs

Reputation: 414225

to save in one specific directory, the same where my script lives

To change the current working directory inside your Python script to a directory where your script lives:

import os

os.chdir(get_script_dir())

where get_script_dir() is defined here.

But then, once you use os.chdir, how do I modify the argument of plt.savefig to make sure my images are saved where my script is?
Would it just be plt.savefig(os.chdir(get_script_dir())+'\image.jpg)?

Use plt.savefig('image.jpg').

Upvotes: 1

Related Questions