[Tutor] critique my script: add columns in a file

Alan Gauld alan.gauld at btinternet.com
Wed Feb 14 10:03:49 CET 2007

"Christopher Spears" <cspears2002 at yahoo.com> wrote

> I modified a script I found in "Programming Python"

I assume it was the first edition of Programming Python?

> #!/usr/bin/python
> import string
> def find_longest_line(fileName):
> longest_col = []
> for lines_in_file in open(fileName, 'r').readlines():

for line in open(fileName):      # no need for readlines now and 'r' 
is default

> cols_in_file = string.split(lines_in_file)

    cols = line.split()  # string module deprecated, use string 

> numCols = len(cols_in_file)
> if numCols > len(longest_col):
> longest_col = cols_in_file

longest = max(longest,len(cols))

> return len(longest_col)

return longest   # save calculating length twice

> def summer(fileName):
> length_longest_col = find_longest_line(fileName)
> sums = [0] * length_longest_col
> for lines_in_file in open(fileName, 'r').readlines():

for line in open(fileName):   # as above

> cols = string.split(lines_in_file)

cols = line.split() # as above

> for i in range(len(cols)):
> sums[i] = sums[i] + float(cols[i])

sums[i] =+ float(cols[i])   # new += operator added

> return sums
> if __name__ == '__main__':
> import sys
> print summer(sys.argv[1])
> What do you think?

Apart from the use of old idioms its OK. Try it with the
changes above, it should be a lot shorter. Also to avoid
iterating over the file twice you could consider capturing
the data into a table and passing that back as well as
the longest line length. You could even return the length
of each line as the first element to avoiud finding it twice.

Just some ideas.

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list