[portland] Array writing question from landscape ecologist

Ethan Furman ethan at stoneleaf.us
Sat Mar 13 05:12:30 CET 2010


Ray Parrish wrote:
> Ethan Furman wrote:
> 
>> lintzh at science.oregonstate.edu wrote:
>>
>> [snippety]
>>
>>>     with open(outfilename,'w') as outfile:
>>>         outfile.write(header)
>>>         for line in data4:
>>>             line.replace('[',' ').replace(']',' ')
>>>             outfile.write(line)
>>
>>
>>           for line in data4:
>>               outfile.write(','.join([str(item) for item in line]))
>>
>>
>> ~Ethan~
> 
> Hello,
> 
> Sorry to jump in here, but I am fairly new to Python programming, and 
> the syntax you are using in your answer is intriguing me. I missed the 
> question, as I just joined this group last night.

Welcome to the group!

> 
> Could you please explain to me what the ','.join() is doing in your 
> write command?
> 

The .join() is a method of string objects.  It is used to join together 
a list of strings into a new string.  For example, if you have the list

--> example = ['this', 'is', 'a', 'list']

then

--> ' '.join(example)
'this is a list'

--> '-'.join(example)
'this-is-a-list'

--> ' * - * '.join(example)
'this * - * is * - * a * - * list'

As you can see, whatever your seperator string is, it gets inserted in 
between each list element to make the new string.

> I understand the code for the loop above, but it is new to me, so if 
> there is a mistake in it, that the question was about, I would 
> appreciate being informed of what I missed to facilitate my ultimate 
> understanding of the with construct, which I am pretty shaky on so far.

The mistake in the original code was the line.replace() -- at that 
point, line is a row from an array which has no replace method, so the 
code errors out.  The fix is to take the the row, convert it into a 
string, and then go from there.  My preference for doing that is usually

--> ','.join(['%s' % item for item in line])

as using the % formating gives plenty of flexibility.

The 'with' statement is standard in Python 2.6.  In 2.5 you have to have 
the statement 'from __future__ import with_statement' at the top of your 
module.  Basically, it allows you take code like this:

--> text_file = open('/some/path/and/file.txt', 'w')
--> try:
-->    for something in a_big_data_object:
-->        text_file.write(something.process())
--> finally:
-->     text_file.close()

and replace it with code like this:

--> with open('/some/path/and/file.txt', 'w') as text_file:
-->     for something in a_big_data_object:
-->         text_file.write(something.process())

and when the loop is done, exception or no, text_file gets closed.  Of 
course, the real fun begins when you write your own context managers for 
use with the 'with' statement.

> 
> Thanks, Ray Parrish

You are welcome.

~Ethan~


More information about the Portland mailing list