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

后端 未结 3 722
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:29

    I am assuming that you are working with 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. You should make sure that the directory for saving the file already exists. If not use os.makedirs to create it first:

    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))
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-06 17:56

    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.

    0 讨论(0)
提交回复
热议问题