Python:如何将文件保存在其他目录中? [英] Python: how do I save a file in a different directory?

查看:380
本文介绍了Python:如何将文件保存在其他目录中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我的Python程序(在UNIX环境中)可以保存文件.

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')

如何在不切换目录的情况下将其保存在新目录中?我想将文件保存在Pics2/force3damping3omega3set2.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.

推荐答案

通过使用完整或相对路径.您只指定一个文件名,没有路径,这意味着它将被保存在当前目录中.

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.

要将文件保存在相对于当前目录的Pics2目录中,请使用:

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')

或更妙的是,使用os.path.join()和字符串格式构造路径:

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)))

最好是使用绝对路径:

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)

这篇关于Python:如何将文件保存在其他目录中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆