4

So right now - my Python program (in a UNIX environment) can save files.

fig.savefig('forcing' + str(forcing) + 'damping' + str(damping) + 'omega' + str(omega) + 'set2.png')

How could I save it in a new directory without switching directories? I would want to save the files in a directory like Pics2/forcing3damping3omega3set2.png.

1

3 Answers 3

8

By using a full or relative path. You are specifying just a filename, with no path, and that means that it'll be saved in the current directory.

To save the file in the Pics2 directory, relative from the current directory, use:

fig.savefig('Pics2/forcing' + str(forcing) + 'damping' + str(damping) + 'omega' + str(omega) + 'set2.png')

or better still, construct the path with os.path.join() and string formatting:

fig.savefig(os.path.join(('Pics2', 'forcing{0}damping{1}omega{2}set2.png'.format(forcing, damping, omega)))

Best is to use an absolute path:

path = '/Some/path/to/Pics2'
filename = 'forcing{0}damping{1}omega{2}set2.png'.format(forcing, damping, omega)
filename = os.path.join(path, filename)
fig.savefig(filename)
Sign up to request clarification or add additional context in comments.

Comments

7

You can join your filename with a full path so that it saves in a specific location instead of the current directory:

import os

filename = "name.png"
path = "/path/to/save/location"
fullpath = os.path.join(path, filename)

Using os.path.join will properly handle the separators, in a platform independent way.

Comments

0

I am assuming that you are working with pylab (matplotlib).

You can use a full path as the fname argument of savefig(fname, ...), which can be either an absolute path like /path/to/your/fig.png or a relative one like relative/path/to/fig.png. You should make sure that the directory for saving the file already exists. If not use os.makedirs to create it first:

import os

... # create the fig

dir = 'path/to/Pics2'
if not os.path.isdir(dir): os.makedirs(dir)
fname = 'forcing' + str(forcing) + 'damping' + str(damping) + 'omega' + str(omega) + 'set2.png'
fig.savefig(os.path.join(dir, fname))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.