0

I got a CSV file which sometimes it's empty and sometimes got content in it. I am trying to check if the CSV is empty or not, so I could know if to append to it or recreate it.

I have tried this:

check_df = pd.read_csv(r'my file')
if check_df.empty:
    csvfile = open(r'my file', 'w', newline='')
    obj = csv.writer(csvfile) 
    obj.writerow(["date", "bmo amc", "stock symbol","company name"])
    print("csv empty")
else:
    csvfile = open(r'my file', 'a', newline='')
    obj = csv.writer(csvfile)
    print("appending csv")  

this code gives me the error:

pandas.errors.EmptyDataError: No columns to parse from file

pretty new to python if you can please be clear with the answers thanks.

bikoman57
  • 116
  • 11

2 Answers2

2

You should check to see if the file is empty using the python library instead of using pandas
in your case the file is 136bytes when empty so:

import os 
if os.path.getsize('my file') < 137:
    csvfile = open(r'my file', 'a', newline='')
    obj = csv.writer(csvfile)
    print("appending csv")  
else:
    csvfile = open(r'my file', 'w', newline='')
    obj = csv.writer(csvfile) 
    obj.writerow(["date", "bmo amc", "stock symbol","company name"])
    print("csv empty")
bikoman57
  • 116
  • 11
Wamadahama
  • 1,489
  • 13
  • 19
  • well, it worked half way it did solve the error, but when there is some content in the csv it just rewrites it and doesn't go to the else condition. the size of my empty file is 136 bytes as written in my pc. also, I would love a short explanation about the `os.path.getsize` – bikoman57 May 29 '19 at 13:51
0

You can also make use of python exception handling to avoid this error

import csv
vFileName='tmp.csv'
try:
    check_df = pd.read_csv(vFileName)
except:
    with open(vFileName, 'w', newline='') as csvfile:
        obj = csv.writer(csvfile) 
        obj.writerow(["dtest", "bmo amc", "stock symbol","company name"])
        print("csv empty")
else:
    with open(vFileName, 'a', newline='') as csvfile:
        obj = csv.writer(csvfile)
        obj.writerow(["dtest", "bmo amc", "stock symbol","company name"])
        print("appending csv") 
Krishna
  • 471
  • 2
  • 7