coverting list back to string
Alex Martelli
aleax at aleax.it
Tue Apr 22 08:47:19 EDT 2003
Dialtone wrote:
> regnivon at netscape.net (scn) writes:
>
>> my quest: i know that output.write(remove) is not correct. you
>> cannot use the 'write' method on a list. is there a better way to
>> convert the list to a string after the first element of the list has
>> been removed and then output the strings to a file? i'm a newbie
>> programmer and need guru help. thank you.
>
> Sure:
>
> input = file('c:/python22/programs/linetest.txt', 'r')
> output = file('c:/python22/programs/output.txt', 'w')
>
> for line in input:
> remove = line.split()
> remove = remove[1:]
> output.write(''.join(remove))
Even better might be to change the last two lines into:
output.writelines(remove[1:])
(the writelines method accepts ANY sequence of strings, not
just lines). If the lines are huge, a tiny but neat
optimization can further be (avoiding constructing the
list needed for the slicing):
for line in input:
fields = iter(line.split())
fields.next()
output.writelines(fields)
Note however that all of these solutions remove whitespace
from the file -- including line-ends &c -- since split
splits on whitespace but the whitespace isn't reinserted
afterwards (neither with the explicit join, nor by the
implicit ones performed by the writelines method). I am
not sure whether this behavior is what the original poster
wants, since I don't have his post on my feed -- it sure
does seem to be what he's asking for, given this partial
quote that I see here, but sometimes what people ask for is
not exactly what they want, so it may be worth double checking.
> input.close()
> output.close()
Leaving these in since they're helpful anyway;-).
Alex
More information about the Python-list
mailing list