[Tutor] Files and such 2

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Oct 2 00:27:23 CEST 2004



On Fri, 1 Oct 2004, Prospero wrote:

> Greetings!
>
> Thanks to Danny, I now have a piece of code that will do most of what I
> want for one line, as follows:-

[code cut]

> However, I need to be able to do this for all lines in the file, going
> forward for one process and backward for another. Is there a simple way
> to count the lines?


Hi Prospero,

Let me restructure that code that you've written in a slightly different
way: I want to bundle up the things that that you're doing to one line as
a single function:


> x = open("numbers.txt","r")
> foo = x.readlines()
> print foo
> bar = foo[0]
> print bar
> chunks = bar.split(',')
> print chunks[0]
> a = chunks[0]
> print a



This can be transformed to:

###
def parseLine(bar):
    print bar
    chunks = bar.split(',')
    print chunks[0]
    a = chunks[0]
    print a

x = open("numbers.txt","r")
foo = x.readlines()
print foo
parseLine(foo[0])
###


I circled around the block that pays attention to a single line in the
file, and made it into a new function called parseLine().


Just as we can use paragraphs in English to group related ideas, we can
use functions to group related program statements.  By moving the
line-parsing stuff in its own function, we can easily call the same
parseLine() on the next few lines like this:

###
parseLine(foo[0])
parseLine(foo[1])
parseLine(foo[2])
parseLine(foo[3])
...
###


But it's still a bit silly to do it this way, since we have no idea how
many lines there are in a file.  In general, if you want to do this
parseLine() function on every element in a list, we can use a 'for' loop.

See:

    http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm

for an example of a 'for' loop.


One other improvement I'd suggest: please avoid using 'foo' and 'bar' as
variable names.  *grin* Instead, try to use more meaningful names, like
'lines' or 'line'.


Good luck to you.



More information about the Tutor mailing list