How to NOT read_csv if csv is empty

Using Python 2.7 and Pandas

I need to parse my directory and build a bunch of CSV. If the CSV is empty, the script terminates and gives an error message:

pandas.io.common.EmptyDataError: No columns to parse from file

If I have file paths stored in

file_paths=[]

How did I read each of them and only built non-empty CSVs? If I have an empty data framework defined as df = [], I am trying to execute the following code

for i in range(0,len(file_paths)):
   if pd.read_csv(file_paths[i] == ""):
      print "empty"
   else df.append(pd.read_csv(file_paths[i],header=None))
+4
source share
2 answers

You can use the built-in syntax tryand exceptto skip files that return an error to you as follows:

Described here: Try / Except in Python: how do you correctly ignore Exceptions?

for i in range(0,len(file_paths)):
   try:
       pd.read_csv(file_paths[i])
       ### Do Some Stuff
   except:
       continue
       # or pass

, , .

0

, python :

import pandas.io.common

for i in range(0,len(file_paths)):
   try:
      pd.read_csv(file_paths[i])
   except pandas.io.common.EmptyDataError:
      print file_paths[i], " is empty"
+4

Source: https://habr.com/ru/post/1669294/


All Articles