[英]Python: how do I save a file in a different directory?
So right now - my Python program (in a UNIX environment) can save files. 所以现在 - 我的Python程序(在UNIX环境中)可以保存文件。
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.
我想将文件保存在像Pics2 / forcing3damping3omega3set2.png这样的目录中。
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: 要将文件保存在
Pics2
目录中,相对于当前目录,请使用:
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: 或者更好的是,使用
os.path.join()
和字符串格式构造路径:
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)
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. 使用
os.path.join
将以独立于平台的方式正确处理分隔符。
I am assuming that you are working with pylab
( matplotlib
). 我假设您正在使用
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
. 你可以使用完整路径作为
savefig(fname, ...)
的fname
参数,它可以是像/path/to/your/fig.png
这样的绝对路径,也可以是像relative/path/to/fig.png
这样的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: 如果不使用
os.makedirs
首先创建它:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.