How to reference a previously created file name in savefig

88 views Asked by At

I am fairly inexperienced with python but I have quite a lot of data (csv) that I need to process and plot in figures. My question is when using plt.savefig how would I reference the figure file name from a file name that I have created previously?

print(f'Output File : {foname_str}') 
plt.savefig(str("{foname_str}"), dpi = 1000)

I want to name the file as exactly the same as my previous file that I have created without going to the directory and copy it's name or its path to plt.savefig(.....). It seems the above snippet of code names the file as foname_str.png instead of the actual name of the file XX_YY_ZZ.

3

There are 3 answers

1
Owen On

I believe you tried to do an f-string (https://docs.python.org/3/tutorial/inputoutput.html), but you forgot the f. Try this:

plt.savefig(f"{foname_str}", dpi = 1000)

If you are running your python file from another directory then it will save in that one.
To get it in the same directory you could do that:

import os

filepath = os.path.join(os.path.dirname(__file__), foname_str)
ext = "png"

plt.savefig(f"{filepath}.{png}", dpi=1000)
0
Gabriel Kalman On

The f-string I had created before had a .csv extension, therefore it couldn't be used by savefig.

I had to remove the extension before saving the file to .png.

0
Trenton McKinney On
  • Use pathlib, for object-oriented filesystem paths, to find the files and use the .stem method to extract the filename, and use an f-string to insert the filename into savefig.
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt

# read the files from the path into a generator
files = Path('D:\\data\\files').glob('*.csv')  # or .rglob to include subdirectories

for file in files:

    # extract the existing filename without the extension from the file path
    file_name = file.stem
    print(file_name)

    # df = pd.read_csv(file)

    ...

    plt.savefig(f'{file_name}.png', dpi=1000)
  • without an f-string
cwd = Path('D:\\data\\files')  # or Path.cwd()
files = cwd.glob('*.csv')

for file in files:

    # print the filename for review
    print(file.stem)

    # df = pd.read_csv(file)

    ...

    plt.savefig((cwd / file.stem).with_suffix('.png'), dpi=1000)