To check whether file is present and is not empty, you need to call the combination of os.path.exists and os.path.getsize with the “and” condition. For example:
import os
my_path = "/path/to/file"
if os.path.exists(my_path) and os.path.getsize(my_path) > 0:
# Non empty file exists
# ... your code ...
else:
# ... your code for else case ...
As an alternative, you may also use try/except with the os.path.getsize (without using os.path.exists) because it raises
OSError if the file does not exist or if you do not have the permission to access the file. For example:
try:
if os.path.getsize(my_path) > 0:
# Non empty file exists
# ... your code ...
else:
# Empty file exists
# ... your code ...
except OSError as e:
# File does not exists or is non accessible
# ... your code ...
References from the Python 3 document
-
os.path.getsize()will:Return the size, in bytes, of path. Raise
OSErrorif the file does not exist or is inaccessible.For empty file, it will return
0. For example:>>> import os >>> os.path.getsize('README.md') 0 -
whereas
os.path.exists(path)will:Return
Trueif path refers to an existing path or an open file descriptor. ReturnsFalsefor broken symbolic links.On some platforms, this function may return
Falseif permission is not granted to executeos.stat()on the requested file, even if the path physically exists.