Skip to main content
Python 3

Python FOR loops

By April 17, 2013September 12th, 2022No Comments

As with any scripting technology the power is in the looping constructs so that we can repeat code quickly and effectively. In this tutorial we look at using FOR loops first, simply to list and Python modules but then the read lines from a file. In reading from the file we also need to take care of blank or empty lines to make sure that if using these values we are not passing bad data to be processed. We will work with Python at the command line and in scripts on an openSUSE 12.3 host. First we look at a simple for loop list modules :

		import sys
		for m in sys.modules:

With this understood and run from both a script and the command line we venture into reading from a file. This will make up part of out project later where we can import users from text files. In a modular fashion we will look at different elements needed to make this happen and combine them togther into the final script.

		f = open("/home/andrew/file1")
		for l in f.readlines():
			if l=="n":