Iterating Over the Lines of a File

This forum allows you to share scripts with other Zeus users. Please do not post bug reports, feature requests or questions to this forum, but rather use it exclusively for posting scripts or for the discussion of scripts that have been posted.
Post Reply
jussij
Site Admin
Posts: 2650
Joined: Fri Aug 13, 2004 5:10 pm

Iterating Over the Lines of a File

Post by jussij »

In creating Zeus macros a common action is iterating over the lines of some file.

The 'c:\temp\test.py' code below shows how easy this is using Python:

Code: Select all

import sys

def main():
    filename = 'c:\\temp\\test.py'

    with open(filename) as lines:
        # enumerate the lines of the file
    	for index, line in enumerate(lines):
    	    # Note: Use stdout as the line already has a line feed
    	    sys.stdout.write('[' + str(index) + ']: ' + line)
main()
Running this code produces the following output:
[0]: import sys
[1]:
[2]: def main():
[3]: filename = 'c:\\temp\\test.py'
[4]:
[5]: with open(filename) as lines:
[6]: # enumerate the lines of the file
[7]: for index, line in enumerate(lines):
[8]: # Note: Use stdout as the line already has a line feed
[9]: sys.stdout.write('[' + str(index) + ']: ' + line)
[10]: main()
Post Reply