How to stop Python from checking for files upon execution
Question: I've got a script I've put together that generates a number of files full of
json data by calling another python module. I then want to be able to import
those after they are generated and do things with the data they contain.

The problem is, when I try to run this script, it complains about the files
not existing. I guess because Python checks for all files to be opened before
executing the code, regardless of where the open statements fall within the
code. Is there a way around this, so it won't try to open the files until
after the generator has called the module to create them? Example code below:

    
    
    #!/usr/bin/python
    
    import os, sys
    import json
    import random
    import ships_levels_stats_generator
    
    def main():
        number = 10
        ships_levels_stats_generator.interface(str(number))
    
        for i in range(0, number):
            with open('../Test/attack%s.json' % i) as attack_json:
                attack_data = json.load(attack_json)
            with open('../Test/hp%s.json' % i) as hp_json:
                hp_data = json.load(hp_json)
            with open('../Test/repair%s.json' % i) as repair_json:
                repair_data = json.load(repair_json)
    
        for key in attack_data.iterkeys():
            if len(attack_data[key]) < 20:
                print "Under 20."
            elif len(attack_data[key]) < 30:
                print "Under 30."
            elif len(attack_data[key]) < 60:
                print "Under 50."
            elif len(attack_data[key]) < 80:
                print "Under 80."
            else:
                print "Over 80."
    


Answer: It's just an indentation issue: the for loop needs to be indented to be part
of your main function. As it is now, it runs when the file is loaded each
time.

