4

I'm creating a custom file writer. I need to write out the values of my array as comma separated into one line in the file. I could do the following:

def as_csv(array):

    return ','.join([str(i) for i in array]) + '\n'

then:

outfile.write(my_header)
outfile.write(other_stuff)
outfile.write(as_csv(array))

but I wonder if this is the most efficient way to do this, or if there would be a better method using the numpy.array_str or numpy.array_repr methods.

2 Answers 2

6

You can also use the built-in numpy method np.savetxt: http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html

np.savetxt(outfile, array, delimiter=',')
Sign up to request clarification or add additional context in comments.

Comments

0

I haven't tried to use np.savetxt in the context below, perhaps it could be used so long as the file is opened in append mode, but here is the solution for what I was trying to do. However, it may not be the most efficient..

def _as_csv(self, values):
    vals = ','.join([str(i) for i in values])
    return vals + '\n'

def output(self, filename, series_cnt, series_name, series_type, startdate, N, values, step = 1000):
    """ outputs data to a file """

    starttime = startdate

    num_imports = (N / step) + 1

    outfile = open(filename.format(series_cnt, i), 'w')
    outfile.write('#{0},{1},{2},\n'.format('TEST', startdate.strftime('%Y%m%d%H%M%S000'), str(num_imports)))


    for i in range(0, N, step):

        line_start = '/Test/{0},{1},{2},{3},'.format(series_name, series_type, starttime.strftime('%Y%m%d%H%M%S000'), step)
        outfile.write(line_start)
        nxt = i + step
        starttime = starttime + dt.timedelta(hours=step)

        outfile.write(self._as_csv(values[i:nxt]))

        outfile.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.