file io (lagged values) newbie question

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Feb 20 16:03:43 EST 2007


Steven D'Aprano a écrit :
> On Tue, 20 Feb 2007 07:08:02 -0800, John Machin wrote:
> 
> 
>>>def write_series(data, f):
>>>    """Write a time series data to file f.
>>>
>>>    data should be a list of integers.
>>>    f should be an already opened file-like object.
>>>    """
>>>    # Convert data into a string for writing.
>>>    s = str(data)
>>>    s = s[1:-1]  # strip the leading and trailing [] delimiters
>>>    s = s.replace(',', '') # delete the commas
>>>    # Now write it to the file object
>>>    f.write(s)
>>>    f.write('\n')
>>
>>And that's not cruft?
> 
> 
> No. Why do you think it is crufty?

Because it is ?
 >
> Would it be less crufty if I wrote it as a cryptic one liner without
> comments?
> 
> f.write(str(data)[1:-1].replace(',', '') + '\n')

Nope. It's still a WTF.

> Okay, it depends on the string conversion of a list.

Nope. It depends on the *representation* of a list.

> But that's not going
> to change any time soon.

> 
>>Try this: f.write(' '.join(str(x) for x in data) + '\n')
> 
> 
> That will only work in Python 2.5 or better.

Really ?

Python 2.4.1 (#1, Jul 23 2005, 00:37:37)
[GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on 
linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> " ".join(str(x) for x in range(10))
'0 1 2 3 4 5 6 7 8 9'
 >>>



More information about the Python-list mailing list