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

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.