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

后端 未结 3 721
Happy的楠姐
Happy的楠姐 2021-01-06 17:02

So right now - my Python program (in a UNIX environment) can save files.

fig.savefig(\'forcing\' + str(forcing) + \'damping\' + str(damping) + \'omega\' + st         


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-01-06 17:44

    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)
    

提交回复
热议问题