2

hi im slowly trying to learn the correct way to write python code. suppose i have a text file which i want to check if empty, what i want to happen is that the program immediately terminates and the console window displays an error message if indeed empty. so far what ive done is written below. please teach me the proper method on how one ought to handle this case:

import os

    def main():

        f1name = 'f1.txt'
        f1Cont = open(f1name,'r')

        if not f1Cont:
            print '%s is an empty file' %f1name
            os.system ('pause')

        #other code

    if __name__ == '__main__':
        main()
user582485
  • 509
  • 3
  • 13
  • 23

6 Answers6

1

There is no need to open() the file, just use os.stat().

>>> #create an empty file
>>> f=open('testfile','w')
>>> f.close()
>>> #open the empty file in read mode to prove that it doesn't raise IOError
>>> f=open('testfile','r')
>>> f.close()
>>> #get the size of the file
>>> import os
>>> import stat
>>> os.stat('testfile')[stat.ST_SIZE]
0L
>>>
AJ.
  • 27,586
  • 18
  • 84
  • 94
1

The pythonic way to do this is:

try:
    f = open(f1name, 'r')
except IOError as e:
    # you can print the error here, e.g.
    print(str(e))
Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
  • You can open an empty file without getting an IOError, the file only has to exist. – AJ. May 10 '11 at 17:34
  • Indeed. And that try.. except keeps the program safe from possible "File Not Found", "Read permission" etc. errors. – Zaur Nasibov May 10 '11 at 17:40
  • 1
    Not saying it's improper to use a try/except...certainly an important thing to do. But the question was how to check for an **empty** file, and I don't see how your answer addresses the question. – AJ. May 10 '11 at 17:45
  • Yep, my bad, misunderstood the question. – Zaur Nasibov May 10 '11 at 18:14
1

Maybe a duplicate of this.

From the original answer:

import os
if (os.stat(f1name).st_size == 0)
    print 'File is empty!'
Community
  • 1
  • 1
abaumg
  • 2,083
  • 1
  • 16
  • 24
0

If file open succeeds the value of 'f1Cont` will be a file object and will not be False (even if the file is empty).One way you can check if the file is empty (after a successful open) is :

if f1Cont.readlines():
    print 'File is not empty'
else:
    print 'File is empty'

sateesh
  • 27,947
  • 7
  • 36
  • 45
0

Assuming you are going to read the file if it has data in it, I'd recommend opening it in append-update mode and seeing if the file position is zero. If so, there's no data in the file. Otherwise, we can read it.

with open("filename", "a+") as f:
    if f.tell():
        f.seek(0)
        for line in f:   # read the file
            print line.rstrip()
     else:
        print "no data in file"
kindall
  • 178,883
  • 35
  • 278
  • 309
0

one can create a custom exception and handle that using a try and except block as below

class ContentNotFoundError(Exception):
    pass
with open('your_filename','r') as f:
    try:
        content=f.read()
        if not content:
            raise ContentNotFoundError()
    except ContentNotFoundError:
        print("the file you are trying to open has no contents in it")
    else:
        print("content found")
        print(content)

This code will print the content of the file given if found otherwise will print the message the file you are trying to open has no contents in it

Arbaaz Ali
  • 119
  • 2
  • 8