R – How to check a file exists and is not empty

Here is another way to check if a file is empty, this time in R!
In the recent past, we posted about How to check if a file is empty in Python, this post looks to build on that and show you in R Programming how to get the same effect.

When looking at the two programming languages, that while the concepts are pretty much the same, the syntax used to achieve the outcome can be slightly different; hence you have to remember which language you are in when writing the code!

Ensure the files exists and open it, gotta be confident it there 🙂

As a preliminary step we check to see if the file exists using:

if(file.exists("emptyfilea.txt")
... rest of your code

 

Then we go and see if the file is empty or not. The full code can be viewed here.

Additional information to help you along the way.

I have referenced this site before, it has some very useful explanations of different functions and methods, for files Check R Documentation

Data Analytics Ireland

 

How to check if a file is empty

Ever wondered how to about checking if a file is empty?

A problem you may come across in Data Analytics that when you are importing a file as outlined in this post Python – How to import data from files is how do we know if the files are empty or not before import?

In the world of data, there are several reasons to check :

  • You have an automated process relying on the import not been empty.
  •  A process that preceded you receiving the file did not work.
  • The amount of time and effort to investigate the problem causes undue work to fix.

The nuts and bolts of it all

Here we have a video that looks at different scenarios on how to bring in files. The following functionality appears in this video:

  • os.path.getsize – This looks to get the file size attached to the file. * Please see note below
  • pd.read_csv
  • pd.read_excel

The add on bits

*One note about os.path.getsize, which we found:

  • It only works in the logic provided if the size of the file is zero KB.
  •  CSV and XLSX files even though they where created empty, when saved had a file size greater than zero.
  •  TXT files, when created empty and saved, had a file size of zero.

 

Hope this video helps explain further how empty files can be checked in python before they are processed.

Thanks!

Data Analytics Ireland