Search code examples
pythonmatplotlibdata-analysis

how to save a certain file name but change the file type in matplotlib.savefig


I have a program to plot data from many files and have a loop to do it and currently have

import matplotlib.pyplab as plt
for file in fireplace
    plotting code
    plt.savefig(file.jpg)

I want to save the figure with the same text name but as a different extension. Lets say the file is data1.txt, then I make the plot and want the plot to be saves as data1.jpg. Is there a way to do this?


Solution

  • Look into the os module:

    import os
    img_filename = os.path.splitext('data1.txt')[0] + '.jpg'