I have a text file. How can I check whether it's empty or not?
11 Answers
>>> import os
>>> os.stat("file").st_size == 0
True

- 4,079
- 3
- 26
- 32

- 327,991
- 56
- 259
- 343
-
3that's fine too. but i don't want to import stat. Its short and sweet enough and the size position in the returned list is not going to change anytime soon. – ghostdog74 Mar 24 '10 at 13:48
-
8Note that the file types work for json, too. Sometimes, json.load() for empty file doesn't work and this provides a good way to handle that case – seokhoonlee Mar 23 '16 at 04:14
-
what if the file only contain new line / empty? wrong answer! – greendino Jun 05 '20 at 00:41
-
6@lone_coder It's not actually empty if it has a newline character in it. – sappjw Sep 08 '20 at 18:43
-
@sappjw but the size still indicates zero. that's why this is wrong – greendino Sep 09 '20 at 00:21
-
@lone_coder this gives me `1`: `echo -en '\n' >/tmp/nl; python -c 'import os; print(os.stat("/tmp/nl").st_size)'` – sappjw Sep 09 '20 at 18:37
-
sometimes file's size is 4Kib even its empty – alper Jan 03 '21 at 19:12
-
What is bad is opening the file, reading it using `read()` and check for a length of zero? – Or b Oct 09 '22 at 09:39
import os
os.path.getsize(fullpathhere) > 0

- 5,956
- 10
- 39
- 40
-
8
-
7What is the difference/advantage using this vs os.state('file').st_size? – Elijah Lynn Nov 25 '17 at 00:30
-
4Looks like the two are the same under the hood: https://stackoverflow.com/a/18962257/1397061 – 1'' Feb 07 '18 at 06:29
-
-
3@alper 20 is the size of a gzipped empty file. If your file was truly empty, with `ls -l` (or `dir` on windows) reporting a size of 0, `os.path.getsize()` should also return 0. – joanis Sep 13 '21 at 14:20
Both getsize()
and stat()
will throw an exception if the file does not exist. This function will return True/False without throwing (simpler but less robust):
import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0

- 1,248
- 11
- 12
-
-
19There is a race condition because the file may be removed between the calls to `os.path.isfile(fpath)` and `os.path.getsize(fpath)`, in which case the proposed function will raise an exception. – s3rvac May 04 '17 at 09:10
-
5Better to try and catch the `OSError` instead, like proposed [in another comment](http://stackoverflow.com/questions/2507808/python-how-to-check-file-empty-or-not/15924160#comment2503155_2507819). – j08lue May 04 '17 at 13:23
-
Also need to catch `TypeError` which will be raised in the event that the input fpath is `None`. – Trutane Sep 19 '19 at 00:17
If you are using Python 3 with pathlib
you can access os.stat()
information using the Path.stat()
method, which has the attribute st_size
(file size in bytes):
>>> from pathlib import Path
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty

- 30,738
- 21
- 105
- 131

- 4,917
- 4
- 33
- 52
If for some reason you already had the file open, you could try this:
>>> with open('New Text Document.txt') as my_file:
... # I already have file open at this point.. now what?
... my_file.seek(0) # Ensure you're at the start of the file..
... first_char = my_file.read(1) # Get the first character
... if not first_char:
... print "file is empty" # The first character is the empty string..
... else:
... my_file.seek(0) # The first character wasn't empty. Return to the start of the file.
... # Use file now
...
file is empty

- 30,738
- 21
- 105
- 131

- 16,489
- 8
- 100
- 116
-
exactly the scenario which i had.. after checking the file, the pointer skipped the first char and i was confused on the final output.... thanks for this... – Nikhil Ravindran Nov 09 '21 at 21:14
if you have the file object, then
>>> import os
>>> with open('new_file.txt') as my_file:
... my_file.seek(0, os.SEEK_END) # go to end of file
... if my_file.tell(): # if current position is truish (i.e != 0)
... my_file.seek(0) # rewind the file for later use
... else:
... print "file is empty"
...
file is empty

- 5,241
- 4
- 28
- 31
-
2This answer is should have more votes because it actually checks whether the file has any contents at all. – amanb Jul 19 '19 at 16:41
Combining ghostdog74's answer and the comments:
>>> import os
>>> os.stat('c:/pagefile.sys').st_size==0
False
False
means a non-empty file.
So let's write a function:
import os
def file_is_empty(path):
return os.stat(path).st_size==0

- 30,738
- 21
- 105
- 131

- 9,178
- 9
- 55
- 88
Since you have not defined what an empty file is: Some might also consider a file with just blank lines as an empty file. So if you want to check if your file contains only blank lines (any white space character, '\r', '\n', '\t'), you can follow the example below:
Python 3
import re
def whitespace_only(file):
content = open(file, 'r').read()
if re.search(r'^\s*$', content):
return True
Explanation: the example above uses a regular expression (regex) to match the content (content
) of the file.
Specifically: for a regex of: ^\s*$
as a whole means if the file contains only blank lines and/or blank spaces.
^
asserts position at start of a line\s
matches any white space character (equal to [\r\n\t\f\v ])*
Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)$
asserts position at the end of a line

- 30,738
- 21
- 105
- 131

- 354
- 4
- 7
-
3I downvoted because 1- there’s no need to define an empty file: it’s a file with no content. A file that contains blank lines is not empty. 2- this reads the whole file in memory. – bfontaine Jan 22 '21 at 10:58
-
1I think this is BAD answer as well. Because it works only for really blank files. But as soon as file is not blank you could face with many errors, one of them `UnicodeDecodeError`. Be careful to use this solution. – hotenov May 24 '21 at 08:53
An important gotcha: a compressed empty file will appear to be non-zero when tested with getsize()
or stat()
functions:
$ python
>>> import os
>>> os.path.getsize('empty-file.txt.gz')
35
>>> os.stat("empty-file.txt.gz").st_size == 0
False
$ gzip -cd empty-file.txt.gz | wc
0 0 0
So you should check whether the file to be tested is compressed (e.g. examine the filename suffix) and if so, either bail or uncompress it to a temporary location, test the uncompressed file, and then delete it when done.
Better way to test size of compressed files: read it directly using the appropriate compression module. You would only need to read the first line of the file, for example.

- 1,279
- 12
- 12
If you want to check if a CSV file is empty or not, try this:
with open('file.csv', 'a', newline='') as f:
csv_writer = DictWriter(f, fieldnames = ['user_name', 'user_age', 'user_email', 'user_gender', 'user_type', 'user_check'])
if os.stat('file.csv').st_size > 0:
pass
else:
csv_writer.writeheader()

- 30,738
- 21
- 105
- 131

- 21
- 1
An easy simple method I used recently is this:
f = open('test.txt', 'w+')
f.seek(0) #Unecessary but important if file was manipulated before reading
if f.read() == '':
print("no data found")
else:
print("Data present in file")
You can use the above as inspiration for your desired uses (keeping in mind I am pretty new to file handling this seemed to suit my desired use in a program I was writing).

- 15
- 3