user2293224
user2293224

Reputation: 2220

Python Pandas: Creating filename before saving dataframe as csv

I am trying to make file name before saving dataframe as csv. Here is my code:

import glob
filename = 'Top20Apps' + ' ' +pd.to_datetime("now").strftime("%Y/%m/%d")+'.csv'

Then I am trying to check whether the any csv file with same name exists or not by following code:

files_present = glob.glob(filename)
    if files_present:
        df.to_csv(filename,index=False,mode='a',header=False)
    else:
        df.to_csv(filename,index=False)

When I ran the above code, it throws the following error:

FileNotFoundError: [Errno 2] No such file or directory: 'Top20Apps 2021/02/01.csv'

Error is showing on the else section. I am not sure where I made the mistake. Any help to fix the issue would be highly appreciated.

Upvotes: 0

Views: 54

Answers (1)

jezrael
jezrael

Reputation: 862511

I think you need change .strftime("%Y/%m/%d") to .strftime("%Y_%m_%d"), because / is not valid value for filename under Windows.

Upvotes: 1

Related Questions