Search code examples
fileloopstry-catchexcept

How to loop over multiple files, ignore empty files without raising an exception?


I'm writing a program that will accept multiple files at once. But I'm trying to change this program in a way that if a empty file is entered, then ignore that file but continue to read over all the other files, and provide me an output without raising any exception errors related to the empty file.

For example:

File 1 = contains text that will work with this program

File 2 = is empty

This is a piece of my program:

from sys import argv
script , filenames = argv[0], argv[1:]

for file in filenames: 
    with open(file) as f: 

        var  = f.read()          

        print "\n\nYou File Name: '(%r)'" % (file)

        var1 = var.split() 
        var2 = len(var1) 

        print '\n\nThe Total Number of Words: "({0:,})"'.format(var2) 

        var3 = var.split()[0]
        var4 = len(var3) 

        print '\n\nThe First Word and Length: "(%s)" ({0:,})'.format(var4)  % (var3)

If I run this program using File 2, I will get the following error:

    var3 = var.split()[0]
IndexError: list index out of range

Is there a way that allows me to run File 1 and File 2 together, but get the output for File 1, then print a message for File 2 saying that its an unrecognizable file? I tried adding try/except but still wasn't working correctly.


Solution

  • Use if / else to check the length of your file:

    for file in filenames: 
        with open(file) as f: 
    
            var = f.read()          
    
            print "\n\nYou File Name: '(%r)'" % (file)
    
            if len(var) > 0:
                var1 = var.split() 
                var2 = len(var1) 
    
                print '\n\nThe Total Number of Words: "({0:,})"'.format(var2) 
    
                var3 = var.split()[0]
                var4 = len(var3) 
    
                print '\n\nThe First Word and Length: "(%s)" ({0:,})'.format(var4)  % (var3)
             else:
                print 'File empty'