NEWBIE TIP: Reading a file two different ways...from ENGSOL

engsol at engsol at
Sat Aug 4 05:59:29 CEST 2001

I'm brand new to Python, and while reading the books,
I tend to bread-board stuff just to see how it works.
I figure it's better to share....
If it's of use to other newbies, great.
If it's in error, please post a correction.
Please excuse the formatting.


# Notice that "foo" indicates you can name the var whatever you care to

class FileRead:                                   # Create the class
    def __init__ (self, foo_filename):            # Name the variable
        self.foo_file = open(foo_filename, 'r')   # Open the file, and name the handle
        while 1:                                  # Do until EOF
            foo_line = self.foo_file.readline()   # Read a line at a time
            if not foo_line:                      # If EOF, bail
                print foo_line,                   # Else display the line via stdout
        self.foo_file.close()                     # Tidy up and close the file

def readfile(foo_name):                           # Pretty much as above
    foo_file = open(foo_name, 'r')
    while 1:
        foo_line = foo_file.readline()
        if foo_line:                              # Notice we change the order of
            print foo_line,                       # the IF, just because we can


# Try the two ways to read a file.....
# While in a NT4 DOS box, and directory = C:\python21
# My command line is: python tags\
# Which invokes stuff above and the next two lines:

FileRead("c:\\python21\\tags\\cauxd.tex")  # Notice the double \\'s



More information about the Python-list mailing list