Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use Variable for filename and have date

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

Here is my code:

companydf.to_csv(r'C:\Users\Admin\exports\test1.csv', index=False)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Desired output:

file_name = example

companydf.to_csv(r'C:\Users\Admin\exports\example m/d/y.csv', index=False)

Thanks

>Solution :

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:\Users\Admin\exports\{file_name}.csv', index=False)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading