Python:如何将文件保存在不同的目录中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13825719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: how do I save a file in a different directory?
提问by InquilineKea
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 Martijn Pieters
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 Pics2directory, 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)
回答by jdi
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.joinwill properly handle the separators, in a platform independent way.
使用os.path.join将以独立于平台的方式正确处理分隔符。
回答by jasxun
I am assuming that you are working with pylab(matplotlib).
我假设您正在使用pylab( matplotlib)。
You can use a full path as the fnameargument of savefig(fname, ...), which can be either an absolute path like /path/to/your/fig.pngor 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.makedirsto create it first:
您可以使用完整路径作为 的fname参数savefig(fname, ...),它可以是绝对路径(例如 )/path/to/your/fig.png或相对路径(例如 )relative/path/to/fig.png。您应该确保保存文件的目录已经存在。如果不使用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))

