Skip to Main Content
Learning Python
book

Learning Python

by Mark Lutz, David Ascher
April 1999
Beginner content levelBeginner
384 pages
11h 15m
English
O'Reilly Media, Inc.
Content preview from Learning Python
  1. Basics, import. This one is simpler than you may think. When you’re done, your file and interaction should look close to the following code; remember that Python can read a whole file into a string or lines list, and the len built-in returns the length of strings and lists:

    % cat mymod.py
    
    def countLines(name):
        file = open(name, 'r')
        return len(file.readlines())
    
    def countChars(name):
        return len(open(name, 'r').read())
    
    def test(name):                                  # or pass file object
        return countLines(name), countChars(name)    # or return a dictionary
    
    % python
    >>> import mymod
    >>> mymod.test('mymod.py')
    (10, 291)

    On Unix, you can verify your output with a wc command. Incidentally, to do the “ambitious” part (passing in a file object, so you only open the file once), you’ll probably need to use the seek method of the built-in file object. We didn’t cover it in the text, but it works just like C’s fseek call (and calls it behind the scenes); seek resets the current position in the file to an offset passed in. To rewind to the start of a file without closing and reopening, call file.seek (0 ); the file read methods all pick up at the current position in the file, so you need to rewind to reread. Here’s what this tweak would look like:

    % cat mymod2.py def countLines(file): file.seek(0) # rewind to start of file return len(file.readlines()) def countChars(file): file.seek(0) # ditto (rewind if needed) return len(file.read()) def test(name): file = open(name, 'r') # pass file object return countLines(file), ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python

Learning Python

Fabrizio Romano
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips

Publisher Resources

ISBN: 1565924649Supplemental ContentCatalog PageErrata