Reputation: 143
I want to be able to check if a CSV file exists in my directory. If it does not, I want to create an empty dataframe with certain columns. If it does I simply want to load that file. The problem is the code reads the else statement and triggers the error of file not found.
if path.exists('raw.csv') == False:
columns = ['join','fund_type','line_type','actual_amount','period','org']
revenueMain = pd.DataFrame(columns=columns)
elif path.exists('raw.csv') == True:
revenueMain = pd.read_csv('rev.csv', header=0)
Upvotes: 4
Views: 5397
Reputation: 2740
I think you have the logic wrong. There is no need for an elif
after the it fails the first if
import os.path as path
if path.exists('raw.csv'):
revenueMain = pd.read_csv('rev.csv', header=0)
else:
columns = ['join','fund_type','line_type','actual_amount','period','org']
revenueMain = pd.DataFrame(columns=columns)
You could also catch the error using:
try:
revenueMain = pd.read_csv('rev.csv', header=0)
except:
columns = ['join','fund_type','line_type','actual_amount','period','org']
revenueMain = pd.DataFrame(columns=columns)
Upvotes: 2