Use Variable for filename and have date

Question:

I am looking to convert a pandas dataframe into a csv and use a variable for the filename.

Here’s the code:

companydf.to_csv(r'C:UsersAdminexportstest1.csv', index=False)

Instead of "test1" for the filename, I’d like to use a variable and have it followed by today’s date.

Desired output:

file_name = example

companydf.to_csv(r'C:UsersAdminexportsexample m/d/y.csv', index=False)
Asked By: BQuist

||

Answers:

This should get you what you need

import datetime
import pandas as pd

#using f-string and datetime you can dynamically set the filename to 'something' and put a date at the end
file_name = f"something_{datetime.datetime.now().strftime('%Y_%m_%d')}"

#This will use a combination of f-string and r-string to make a raw string referencing the filename from above
companydf.to_csv(fr'C:UsersAdminexports{file_name}.csv', index=False)
Answered By: ArchAngelPwn
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.