Help! Cannot open a file in a class

Steven Taschuk staschuk at telusplanet.net
Tue Mar 4 01:36:47 EST 2003


Quoth ouj:
> I am new to Python. I write a class that opens a file and reads the
> data from the file.
> 
> class Cvdoc:
>     def __init__(self):
>         ......
>         fd = file('vdoc.dat', 'wr')
>         print dir(fd)
>         fd.readlines()

'wr' is not a valid mode; file() is just ignoring the 'r' and
opening the file for writing, causing your code to fail when it
tries to read.

If you want to be able to both read and write in the file, you
want 'r+' or 'w+'.

    >>> f = open('foo', 'w+')
    >>> start = f.tell()
    >>> f.write('spam')
    >>> f.seek(start)
    >>> f.read()
    'spam'

(Note also that you have to use tell and seek to move back to the
start of the file, to read the data you wrote.)

See the Library Reference, section 2.2.8 ("File Objects").

-- 
Steven Taschuk             "The world will end if you get this wrong."
staschuk at telusplanet.net    (Brian Kernighan and Lorrinda Cherry,
                            "Typesetting Mathematics -- User's Guide")





More information about the Python-list mailing list