[Tutor] re.format a file
Martin Walsh
mwalsh at mwalsh.org
Thu Feb 26 20:59:25 CET 2009
A.T.Hofkamp wrote:
> prasad rao wrote:
>> helloThank you Lie and Kent.
>> I forgot about newline character and the fact that string can be sliced.
>> Thanks for your timely help
>> BTW I have gone through the Python library reference and find no
>> examples
>> in fileinput module.
>
> The fileinput module only deals with reading and writing data from/to
> files, it does not deal with manipulating that data.
>
> How to manipulate strings is in the 'strings' or 'text' section of a
> tutorial.
>
>> z=fileinput.input(file,inplace=1)
>> for line in z:
>> ???if len(line)<60:pass
>> ???if len(line)>60:
>> ??????line=line[:60]+'\n'+line[60:]
>> Is it the right way to do?
>
> A nice step forward, I'd say.
>
> Did you consider what to do with ridiculous long lines, eg 200, 500,
> 1000 or 10000 characters long?
> If you want to deal with them, you'd need to repeatedly split the line.
> You could use a while loop for it.
Or if the lines resemble paragraphs, then one might use the textwrap
module which breaks on word boundaries by default I think, and provides
several options for tweaking -- perhaps not what the OP is looking for.
# untested
import textwrap
for line in z:
line = textwrap.fill(line, width=60)
HTH,
Marty
More information about the Tutor
mailing list