lily
lily

Reputation: 33

How to save each output by iteration of a loop in separate csv files

I have a file in which i calculate a startdate and enddate, these dates change by iteration each time between a range of dates. the code works fine but i don't know how to save each output seperately in csv files.

My current code saves the first output of the loop only and save it in different csv files.

from pandas.tseries.offsets import MonthEnd
from datetime import datetime, timedelta,date
import numpy as np
from pathlib import Path
import glob
import pandas as pd



for firstdate in pd.date_range('2022-01-01', '2025-12-31', freq='MS'):
startdate = firstdate.date()
enddate = (startdate + MonthEnd(1)).date()
df['slicing_startdate'] = np.where(((df.contractstartdate.dt.date.isnull()) | 
 (df.contractstartdate.dt.date < startdate)), startdate, df.contractstartdate.dt.date)
df['slicing_enddate'] = np.where(((df.effectiveenddate.dt.date.isnull()) | (enddate < 
df.effectiveenddate.dt.date)), enddate, df.effectiveenddate.dt.date)

folder_path= r".../FileName.csv"
months = ['M1','M2','M3','M4','M5','M6','M7','M8','M9','M10','M11','M12','M13','M14','M15','M16','M17','M18','M19','M20','M21','M22','M23','M24','M25','M26','M27','M28','M29','M30','M31','M32','M33','M34','M35','M36']
    for month in months:
    p = Path(folder_path).parent.joinpath(f"BD_{month}.csv")
    if not p.is_file():
        df.to_csv(p,index=False)
    else:
        print('file exists')

So in each csv file under the name of BD_M1, BD_M2, ....etc i have the same slicingstardate = 01/01/2022 and slicingenddate = 31/01/2022. while the desired output is for each csv file i have the corresponding dates.

thanks a lot for your help!

Upvotes: 3

Views: 750

Answers (1)

n1colas.m
n1colas.m

Reputation: 3989

You could remove the second for loop and use enumerate instead, this way you link each data_range iteration to an increasing counter (month) in the same loop.

from pandas.tseries.offsets import MonthEnd
from datetime import datetime, timedelta,date
...

...

folder_path= r"../FileName.csv"

for month, firstdate in enumerate(pd.date_range('2022-01-01', '2025-12-31', freq='MS'), 1):
    startdate = firstdate.date()
    enddate = (startdate + MonthEnd(1)).date()
    df['slicing_startdate'] = np.where(((df.contractstartdate.dt.date.isnull()) | 
    (df.contractstartdate.dt.date < startdate)), startdate, df.contractstartdate.dt.date)
    df['slicing_enddate'] = np.where(((df.effectiveenddate.dt.date.isnull()) | (enddate < 
    df.effectiveenddate.dt.date)), enddate, df.effectiveenddate.dt.date)

    p = Path(folder_path).parent.joinpath(f"BD_M{month}.csv")
    if not p.is_file():
        df.to_csv(p,index=False)
    else:
        print('file exists')

Upvotes: 1

Related Questions