JAG2024
JAG2024

Reputation: 4317

How to write csv file name based on month, year, time column headers in python

This is probably an easy question for someone out there to answer. I have a bunch of csv files that I would like to rename using info from within the file.

I have a data frame result that looks like this:

              id  year  month  day  precip
0       pod_0001  2017      1    1     2.6
1       pod_0002  2017      1    1     0.4
2       pod_0003  2017      1    1     2.2
3       pod_0004  2017      1    1    25.2
4       pod_0005  2017      1    1    19.4

And I want the name of the file to be YYYY.MM.DD, so in this case it would look like result.2017.01.01.

How do I do that with the to_csv function like this one..?

result.to_csv("result.csv", na_rep="0")

Upvotes: 1

Views: 361

Answers (1)

DYZ
DYZ

Reputation: 57085

This solution may be somewhat old-schooled (it uses the % operator), but it works:

fname = "result.%04d.%02d.%02d.csv" % \
        tuple(result[['year','month','day']].drop_duplicates().values[0])
print(fname)
# result.2017.01.01.csv
result.to_csv(fname, na_rep="0")

Upvotes: 1

Related Questions