Linux > python > file-I/O ?

David Wahler dwahler at gmail.com
Sat Dec 24 12:06:03 EST 2005


n... at absamail.co.za wrote:
> I've just started to test/learn python.
> I've got Linux > mandrake9 > python  & documentation.
> What I'll initially want to be doing needs file I/O, so I
> wanted to confirm file I/O early in my tests.
>
> Following the examples :
> >>> f=open('/tmp/workfile', 'w')
> >>> print f
> <open file '/tmp/workfile', mode 'w' at 80a0960>   <-- OK
>
> But:
> >>> f.read(size)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'size' is not defined  <-- ?? Obj-method unknown ??

The expression "f.read(size)" means: take the object referred to by "f"
(a variable), and call the method named "read" with a single parameter,
determined by the expression "size". Since you haven't declared a
variable called size, Python has no idea what you're talking about. You
have to either assign a value to size, or pass in a number directly, as
in "f.read(1000)". You can also call the read method with no parameters
to read the entire contents of the file.

Even if you do this, you'll still have problems because passing the
parameter "w" to the open function means that you're opening the file
in write-only mode. If you want to read from it, you'll need to use
"r", "r+" or "w+" instead.

Hope this helps.

-- David




More information about the Python-list mailing list