0

I run the python code for Matplotlib plotting from thisfilename.py. Is there a variable that stores this filename without file path? As I want to save the plot as thisfilename.png without typing the file name like this every time?

if __name__ == '__main__':
  ...
  plt.savefig('thisfilename.png')

I want to change the last line to something like

  # pseudocode
  plt.savefig(variable, '.png')

I tested

  plt.savefig(__file__, ".png")

The saved filename had .py, the file path, and the space before .png which I don't want

Jan
  • 1,389
  • 4
  • 17
  • 43
  • 1
    Check out [this question](https://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing#1955163) – Tom de Geus Jun 06 '17 at 07:19

3 Answers3

2

To save the figure with same name as the python file, replacing the ".py" by ".png" and removing the path, I would use :

plt.gcf().savefig(__file__.rstrip('.py').split('/')[-1] + ".png")

the rstrip removes ".py" from the right side of the file string, the split method separate your chains at each "/" and [-1] keeps only the last item of the list the + can be used to concatenate strings

user2660966
  • 940
  • 8
  • 19
1
import inspect
import matplotlib.pyplot as plt
import numpy as np

frame = inspect.currentframe()
path = inspect.getfile(frame)
fname = path.split('.')[0]

t = np.linspace(0,1, 1000)
plt.plot(t, np.sin(2*np.pi*t*4))
plt.savefig(fname + ".jpg")
MaxPowers
  • 5,235
  • 2
  • 44
  • 69
1

You can use Python's splitext() to break __file__ into two parts and then add the required extension as follows:

import os

output_filename = os.path.splitext(__file__)[0] + '.png'
plt.savefig(output_filename)
Martin Evans
  • 45,791
  • 17
  • 81
  • 97