Search code examples
pythonfileis-empty

How to confirm that a file object is empty? [Python]


in a py module, I write:

outFile = open(fileName, mode='w')
if A:
    outFile.write(...)
if B:
    outFile.write(...)

and in these lines, I didn't use flush or close method. Then after these lines, I want to check whether this "outFile" object is empty or not. How can I do with it?


Solution

  • If you've already written to the file, you can use .tell() to check if the current file position is nonzero:

    >>> handle = open('/tmp/file.txt', 'w')
    >>> handle.write('foo')
    >>> handle.tell()
    3
    

    This won't work if you .seek() back to the beginning of the file.