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.

Facundo Casco
  • 10,065
  • 8
  • 42
  • 63
InquilineKea
  • 891
  • 4
  • 22
  • 37

3 Answers3

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
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.

jdi
  • 90,542
  • 19
  • 167
  • 203
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))
jasxun
  • 571
  • 1
  • 5
  • 11