Reputation: 11
I'm new to python. I'd like python to pick the correct csv file from a folder. I'd like to compare CDS spreads from the most actual file (t) with yesterday's file (t-1).
Hence, the Code has to choose today's file and the yesterday's file. "Yesterday's" file can be as of yesterday or the day before yesterday.
The Code below identifies the files, but creates yesterday's dataframe with the last date in the Code.
today = dt.date.today()
d1 = today.strftime("%Y%m%d")
print(d1)
t2 = today - timedelta(days = 1)
t3 = today - timedelta(days = 2)
t4 = today - timedelta(days = 3)
t2 = t2.strftime("%Y%m%d")
t3 = t3.strftime("%Y%m%d")
t4 = t4.strftime("%Y%m%d")
print(t2)
print(t3)
print(t4)
if (os.path.exists(path'+d1+'.csv')):
dataframe2 = pd.read_csv(path'+d1+'.csv')
if (os.path.exists(path-'+t2+'.csv')):
dataframe2 = pd.read_csv(path'+t2+'.csv')
if (os.path.exists(path'+t3+'.csv')):
dataframe2 = pd.read_csv(path'+t3+'.csv')
if (os.path.exists(path-'+t4+'.csv')):
dataframe2 = pd.read_csv(path'+t4+'.csv')
How to tell python, if the first file exits, build a dataframe and stop checking the following Dates?
Upvotes: 1
Views: 37
Reputation: 1076
A more flexible way would be using a loop that decreases the date until a file is found, then stop:
t = dt.date.today()
d = today.strftime("%Y%m%d")
max_iter = 100
found = False
while max_iter > 0:
print(d)
if os.path.exists(path+d+'.csv'):
found = True
break
t = t - timedelta(days = 1)
d = t.strftime("%Y%m%d")
max_iter = max_iter - 1
if found:
dataframe = pd.read_csv(path+d+'.csv')
else:
print("No valid file found.")
I also added a counter max_iter
that limits the number of times the loop runs, so that it finishes even if there are not files to be found.
Upvotes: 0