file io (lagged values) newbie question

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Feb 20 08:22:20 EST 2007


On Mon, 19 Feb 2007 22:17:42 -0800, hiro wrote:

> Hey there, I'm currently doing data preprocessing (generating lagged
> values for a time series) and I'm having some difficulties trying to
> write a file to disk.  A friend of mine, wrote this quick example for
> me:

If that's a quick example (well over 100 lines), I'd hate to see your
idea of a long example.

Can you cut out all the irrelevant cruft and just show:

(1) the actual error you are getting
(2) the SMALLEST amount of code that demonstrates the error

Try to isolate if the problem is in *writing* the file or *generating*
the time series.

Hint: instead of one great big lump of code doing everything, write AT
LEAST two functions: one to read values from a file and generate a time
series, and a second to write it to a file.

That exercise will probably help you discover what the problem is, and
even if it doesn't, you'll have narrowed it down from one great big lump
of code to a small function.

To get you started, here's my idea for the second function:
(warning: untested)

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 this is how you would use it:

f = file('myfile.txt', 'w')
# get some time series data somehow...
data = [1, 2, 3, 4, 5]  # or something else
write_series(data, f)
# get some more data
data = [2, 3, 4, 5, 6]
write_series(data, f)
# and now we're done
f.close()


Hope this helps.



-- 
Steven.




More information about the Python-list mailing list