Julian - 1 year ago 109

Python Question

I loop over files and for each of these files, I compute a list of 4000+ (fixed number) features on it. These features are computed by a function and returned as

`numpy.array`

I want to write a CSV file with one line per file (each line is one

`numpy.array`

I'm currently using the

`csv`

`np.around`

`0,302499999999999`

`0,3025`

I know this may come from floating points limitations in Python, but i wanted to know if there is any way to avoid this (by writing it as a string?) in the output file.

Sample of code below to reproduce the issue :

`import numpy as np`

import csv

for i in range(10) :

row = np.around(np.random.random(4000), decimals=5)

with open('output.csv', "ab") as fp:

wr = csv.writer(fp, dialect='excel')

wr.writerow(row)

Answer Source

You can use `numpy.savetxt()`

like this:

```
import numpy as np
with open('output.csv', 'w') as fh:
for i in range(10): # loop over features
row = np.random.random(4000)
np.savetxt(fh, row.reshape(1, -1), fmt='%.5e', delimiter=',')
```