Home > Software engineering >  How to create new excel file each time when I save DataFrame in Python Pandas?
How to create new excel file each time when I save DataFrame in Python Pandas?

Time:06-02

I have function in Python Pandas like below (it is sample):

def xyz():
    df = pd.DataFrame({"a" : [1,1,1]})
    TodaysDate = time.strftime("%Y-%m-%d")
    excelfilename = "raport_"  TodaysDate  ".xlsx"
    df.to_excel(excelfilename, sheet_name="raport", index=True)

    return df

Every time I run above function the existing excel file gets overwritten but I need a new excel file to be created every time I run the function. How can I modify my function to do that in Python ?

CodePudding user response:

Maybe something like this. Depends on how many excel files you want to generate.

import random
excelfilename = "raport_"   str(random.randrange(9999))  TodaysDate  ".xlsx"

CodePudding user response:

You can change TodaysDate = time.strftime("%Y-%m-%d") to TodaysDate = str(time.strftime("%Y-%m-%d %X")).replace(":", "") or TodaysDate = str(TodaysDate.strftime("%Y-%m-%d %H%M%S"))

This will give you an additional Hour/Minute/Seconds for the creation of your excel. So unless you are running this function multiple times a second this should cover your needs.

CodePudding user response:

So you can do in this way:

def xyz(itr):
    df = pd.DataFrame({"a" : [1,1,1]})
    TodaysDate = time.strftime("%Y-%m-%d")
    excelfilename = "raport_"  TodaysDate   str(itr)   ".xlsx"
    df.to_excel(excelfilename, sheet_name="raport", index=True)

    return df

for i in range(9): #or smth another iteration
    xyz(i)

CodePudding user response:

You should really use ArchAngelPwn's solution in my opinion. Applying random numbers might work but you still run the 1/1000 chance that one file will get overwritten. Also, you might not know which file belongs to which loop/run.

You could also save your file names in a list and check if it exists :

fn = []
def xyz():
    df = pd.DataFrame({"a" : [1,1,1]})
    TodaysDate = time.strftime("%Y-%m-%d")
    excelfilename = "raport_"  TodaysDate  ".xlsx"
    temp = len(np.where((np.array(fn) == excelfilename)))
    fn.append(excelfilename)
    df.to_excel("raport_"  TodaysDate   "_"   temp   ".xlsx", sheet_name="raport", index=True)

return df

CodePudding user response:

Its because % in your excelfilename becase you are using %X.

Just change:

TodaysDate = time.strftime("%Y-%m-%d %X")

To:

TodaysDate = time.strftime("%Y-%m-%d %H_%M_%S")

I have double checked and its worked on my side :))

For full code:

import pandas as pd
import time


def xyz():
    df = pd.DataFrame({"a": [1, 1, 1]})
    TodaysDate = time.strftime("%Y-%m-%d %H_%M_%S")
    excelfilename = "raport_"   TodaysDate   ".xlsx"
    df.to_excel(excelfilename, sheet_name="raport", index=True)

    return df


xyz()
  • Related