file io (lagged values) newbie question

John Machin sjmachin at lexicon.net
Tue Feb 20 10:08:02 EST 2007


On Feb 21, 12:22 am, Steven D'Aprano
<s... at REMOVE.THIS.cybersource.com.au> wrote:
> 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 that's not cruft?

Try this: f.write(' '.join(str(x) for x in data) + '\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()
>

Or for a more general solution, use the csv module:

C:\junk>\python25\python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> wtr = csv.writer(open('fubar.txt', 'wb'), delimiter=' ')
>>> data = [0, 1, 42, 666]
>>> wtr.writerow(data)
>>> wtr.writerow([9, 8, 7, 6])
>>> ^Z

C:\junk>type fubar.txt
0 1 42 666
9 8 7 6

HTH,
John




More information about the Python-list mailing list