Subclassing file class

D

David Vaughan

I'm using v2.3, and trying to write to text files, but with a maximum
line length. So, if a line is getting too long, a suitable ' '
character is replaced by a new line. I'm subclassing the file class,
and, as long as I just use the write method, this works fine. But
"print >>" doesn't behave as I want:

class max_width_file(file):
def write(self, txt):
print "In max_width_file's write method."
fout = max_width_file('foo.txt', 'w')
print >> fout, 'bar'
fout.close()

bypasses my write method and prints 'bar' directly to the file. That
isn't the behaviour I inferred from

http://docs.python.org/ref/print.html

How do I intercept "print >>"? Has anyone already implemented this?
And should the documentation be changed?

Any help very welcome.
David



David Vaughan
Structural Analyst
for Gifford

GIFFORD AND PARTNERS LTD
Carlton House, Ringwood Road, Woodlands,
Southampton, SO40 7HT, UNITED KINGDOM

Tel: +44 (0)23 8081 7500 Fax: +44 (0)23 8081 7600
Email: (e-mail address removed)
Web: http://www.gifford.uk.com

This e-mail and any files transmitted with it are intended solely for
the use of the individual or entity to whom they are addressed and may
be confidential. If you are not the intended recipient or the person
responsible for delivering the e-mail to the intended recipient, be
advised that you have received this e-mail in error and that any use,
dissemination, forwarding, printing or copying of this e-mail is
strictly prohibited.
 
M

Michael Hudson

David Vaughan said:
I'm using v2.3, and trying to write to text files, but with a maximum
line length. So, if a line is getting too long, a suitable ' '
character is replaced by a new line. I'm subclassing the file class,
and, as long as I just use the write method, this works fine. But
"print >>" doesn't behave as I want:

You'll almost certainly be happier implementing a 'file-like object'
that does what you want than subclassing file.

Cheers,
mwh
 
C

Christos TZOTZIOY Georgiou

I'm using v2.3, and trying to write to text files, but with a maximum
line length. [snip]

Apart from any other advices you get, you might want to consider the
textwrap module.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top