Custom Filepath Exporting a Pandas Dataframe

Viewed 15

I am working with financial data, and I am cleaning the data in Python before exporting it as a CSV. I want this file to be reused, so I want to make sure that the exported files are not overwritten. I am including this piece of code to help with this:

# Fill this out; this will help identify the dataset after it is exported
latestFY = '21'
earliestFY = '19'

I want the user to change the earliest and latest fiscal year variables to reflect the data they are working with, so when the data is exported, it is called financialData_FY19_FY21, for example. How can I do this using the to_csv function?

Here is what I currently have:

mergedDF.to_csv("merged_financial_data_FY.csv", index = False)

Here is what I want the file path to look like: financialData_FY19_FY21 where the 19 and 21 can be changed based on the input above.

1 Answers

You can use an f-string to update the strings that will be your file paths.

latestFY = '21'
earliestFY = '19'
filename = f"merged_financial_data_FY{earliestFY}_{latestFY}.csv"
mergedDF.to_csv(filename, index=False)

Link to docs

Related