Return os.path.exists(file_path) and os.stat(file_path).st_size = 0 ''' Check if file is empty by confirming if its size is 0 bytes''' So, let’s create a separate function to check if file exists and it is empty i.e. Therefore we should first check if the file exists or not before calling os.stat(). FileNotFoundError,įileNotFoundError: The system cannot find the file specified: FILE_NAME
We already had an empty file ‘mysample.txt’ in the same directory.īut we should be careful while using it because if the file doesn’t exist at the given path, then it can raise an Error i.e.
Let’s use this to get the size of the file ‘mysample.txt’ and if size is 0 then it means, file is empty i.e.Īs our file is empty, so the output will be, One of these attributes is st_size, which tells about the size of the file in bytes.
It accepts file path (string) as an argument and returns an object of the structure stat, which contains various attributes about the file at the given path. Os.stat(path, *, dir_fd=None, follow_symlinks=True) Python provides a function to get the statistics about the file, its size is 0 using os.stat() or os.path.getsize() or by reading its first character.Ĭheck if a file is empty using os.stat() in Python
In this article, we will discuss different ways to check if a file is empty i.e.