converting list back to string
Alex Martelli
aleax at aleax.it
Tue Apr 22 17:47:10 EDT 2003
On Tuesday 22 April 2003 07:30 pm, regnivon at netscape.net wrote:
> Alex,
>
> Thank you for responding to my post. I've included a copy of my original
> post because you said that it wasn't included on your feed. Here it is:
Thanks! Putting python-list back in, though...
> my code:
>
> import xreadlines
>
> input = open('c:/python22/programs/linetest.txt', 'r') # 3 lines of
> text
>
> output = open('c:/python22/programs/output.txt', 'w')
>
> for line in input.xreadlines():
> remove = line.split()
> remove[0:1] = []
> output.write(remove)
>
> output.close()
> input.close()
If what you want is to remove the first field and let the rest of
each line unchanged, best might be (in Python 2.2 or better):
input = open('c:/python22/programs/linetest.txt', 'r')
output = open('c:/python22/programs/output.txt', 'w')
# loop directly on the file open for reading -- xreadlines is obsolescent
for line in input:
# split selectively so most whitespace in the line's not disturbed
first_field, rest_of_line = line.split(None, 1)
output.write(rest_of_line)
output.close()
input.close()
i.e., this approach involves no lists at all.
> 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
You could use output.writelines(remove), but that wouldn't give you
back your lost whitespace;-).
> this part of the program. By the way, I have purchased the Python Cookbook
> and have been learning a lot about programming. I appreciate you taking
> the time to help write the book and to answer my question. I'm certainly a
Hope you're liking the Cookbook! It may be aimed at programmers a bit
more experienced than you currenlty are, but I hope this just means you'll
be enjoying it for longer;-).
> newbie programmer, but Python seems to be the way to go. Scott
Absolutely -- there's no looking back from it!-).
Alex
More information about the Python-list
mailing list