Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how do I save a file in a different directory?

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.

like image 960
InquilineKea Avatar asked Dec 08 '22 19:12

InquilineKea


1 Answers

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)
like image 178
Martijn Pieters Avatar answered Dec 11 '22 08:12

Martijn Pieters