Search code examples
pythonpandasdataframeis-empty

Check if dataframe in text file empty before importation


I am new user of pandas and I need some help. I have in one folder 10 txt files:

file_date1_1.txt
...
file_date1_5.txt
file_date2_1.txt
...
file_date2_5.txt

Each file has the same design:

- text to explain the file
- datas. 

To export one file, I do the following code:

Data_Frame = pd.read_csv(Location,  delimiter=r'\s+', index_col=False, header = None, skiprows=11)

What I want to do is to do a loop to make a list of dataframes. So I did that:

for i in range(0,len(files_SE)):
    date.append(files_SE[i][0:7])
    hour.append(files_SE[i][8:13])
    Location.append('\\'.join([adress,files_SE[i]]))
    SE_df.append(pd.read_csv(Location[i],  delimiter=r'\s+', index_col=False, header = None, skiprows=11))

(skiprows is to avoid the text before the datas and files_SE is a list with all names files).

But my problem is that the loop stops at file_date1_5.txt because there is no data in (it is empty). What I would like is to make a condition such as

if (pd.read_csv(Location[i],  delimiter=r'\s+', index_col=False, header = None, skiprows=11)).empty:
    *do nothing*
else:
    *do the importation of the dataframe*

Does anyone has a solution for me ? Thanks a lot


Solution

  • You can do the check like this:

    Current_Data = pd.read_csv(Location[i],  delimiter=r'\s+', index_col=False, header = None, skiprows=11)
    if not Current_Data.empty:
        SE_df.append(Current_Data)