0

We can assign an empty dataframe with pandas.

import pandas as pd
zero = pd.DataFrame()
zero
Empty DataFrame
Columns: []
Index: []

The zero dataframe is empty containing nothing in it,create a empty data file containing nothing in it.

fh = open('/tmp/test.txt','w')
fh.close()

The file /tmp/test.txt is empty.

newzero = pd.read_csv('/tmp/test.txt',header=None)
pandas.errors.EmptyDataError: No columns to parse from file

How to make pandas read an empty file and assign it as a empty dataframe such as zero shows ? Is there a way to add some argument to make the below commands running without error info.

newzero = pd.read_csv('/tmp/test.txt',header=None,add some argument)
newzero
Empty DataFrame
Columns: []
Index: []
showkey
  • 482
  • 42
  • 140
  • 295

2 Answers2

1

This seems to be the straightforward way of doing it :

import pandas as pd
fh = open('/tmp/test.txt','w')
fh.close()

try:
    newzero = pd.read_csv('/tmp/test.txt',header=None)
except pd.errors.EmptyDataError:
    new_zero = pd.DataFrame()
Partha Mandal
  • 1,391
  • 8
  • 14
0

You can catch exception and create a empty data frame

import pandas as pd
zero = pd.DataFrame()
fh = open('/tmp/test.txt','r')
fh.close()
try:
    newzero = pd.read_csv('test.txt',header=None)
except pd.errors.EmptyDataError:
    newzero = pd.DataFrame()
        
xszym
  • 928
  • 1
  • 5
  • 11