How to check if a file is empty in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To check check if a file is empty or not golang os.stat().st_size method just pass you filename with path in os.stat().st_size method it will return file size if size is 0 means file is empty else file is not empty.

Today, I’m going to show how do i check if a file is empty in golang, as above mentioned I’m going to use the os.stat() method to check the file is blank or not.

Let’s start today’s tutorial how to check if a file is empty in golang?

let’s write a code.

package main

import (

func main() {
	check_file = os.stat("sample.txt").st_size

	if(check_file == 0):
  		print("The file is empty.")
	    print("The file is not empty.")

The os.stat() method provide details about statistics of file and here using st_size we are trying to get file size. let’s see on output which file empty or which not.

All the best 👍

Follow me on Twitter