Home > Software engineering >  Saving data in csv file in Python
Saving data in csv file in Python

Time:06-17

I want to save the data in a csv file in a specific format but I am getting an error. The desired output is attached.

import numpy as np
import csv
N=2
Pe = np.array([[[128.22918457, 168.52413295, 209.72343319],
        [129.01598287, 179.03716051, 150.68633749],
        [131.00688309, 187.42601593, 193.68172751]],

       [[ 64.11459228,  84.26206648, 104.86171659],
        [ 64.50799144,  89.51858026,  75.34316875],
        [ 65.50344155,  93.71300796,  96.84086375]]])

with open('Test123.csv', 'w') as f: 
    for x in range(0,N): 
        print([Pe[x]]) 
        writer = csv.writer(f)
        # write the data 
        writer.writerows(zip(x,Pe[x]))

The error is

TypeError: 'int' object is not iterable

The desired output is

enter image description here

CodePudding user response:

with open('Test123.csv', 'w') as f:
    for x in range(0 ,N):
        print([Pe[x]])
        writer = csv.writer(f)
        # write the data
        header = [x] * len(Pe[x])
        # header = [x]   ['']*(len(Pe[x])-1)
        writer.writerows(zip(header, Pe[x]))

In zip function, parameter needs __iter__ function to execute.

So TypeError: 'int' object is not iterable error occured because int object doesn't have this function.

Make x variable to list type then it works.

CodePudding user response:

Replace

writer.writerows(zip(x,Pe[x]))

with

writer.writerows(zip([x],[Pe[x]]))

This is happening because indexing will give back the object and not an iterable container here

CodePudding user response:

The problem is in the zip function, which expects an iterable (something we can loop over). You can simply write a line to the file instead. I haven't found a great method yet, but this is what I came up with.

I also recommend using the len() function instead of setting an n manually, as well as using snake_case (for your variables too!).

import numpy as np

pe = np.array([[[128.22918457, 168.52413295, 209.72343319],
        [129.01598287, 179.03716051, 150.68633749],
        [131.00688309, 187.42601593, 193.68172751]],

       [[ 64.11459228,  84.26206648, 104.86171659],
        [ 64.50799144,  89.51858026,  75.34316875],
        [ 65.50344155,  93.71300796,  96.84086375]]])

# Loop over the subarrays in pe
with open('Test123.csv', 'w') as f: 
    for i in range(len(pe)):
        # Create the line by appending the index and the array, separated by a comma.
        line = str(i)   ','   str(pe[i])
        
        # Add the number and the subarray
        f.write(line)

P.s.: if you include a line number with your error next time it is easier to help you!

Update: the methods where you use writerows from the other answers are probably nicer, but I hope this answer is useful to you anyway.

  • Related