Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 7314

Python • making a data object iterable

$
0
0
I'm working on a program to parse CSV files. I intend to read each line of each CSV file, order it in a manner that makes sense to me, then write it out to a new composite csv. For the purpose of illustrating the question i'm about to ask i have written the SSCE below:

Code:

#this routine explores the use of the CSV read and write functions.import csvfrom datetime import dateclass order:    def __init__(self, in_row ):        self.Name = in_row[0]        self.DOB = in_row[1]        self.POB = in_row[2]        self.OrderNo = in_row[3]        self.Date = date.today()        with open('/home/pi/Desktop/Test Data.csv', 'r') as infile:    reader = csv.reader(infile)    with open('/home/pi/Desktop/Test Out.csv','a')as outfile:        writer = csv.writer(outfile)        for row in reader:            in_row = next(reader)            lorder = order(in_row)            writer.writerow(lorder)
when i run it without breakpoints i get the following error message:

File "/home/pi/Python code/CSV Read Write.py", line 23, in <module>
writer.writerow(lorder)
_csv.Error: iterable expected, not order

line 23 is the call to the writer.writerow(lorder) function

i looked on the internet and got the following AI generated python code to make my data class iterable. The problem is I do not fully understand what its doing and I hesitate to copy and paste without understanding

Code:

class MyIterable:    def __init__(self, data):        self.data = data        self.index = 0    def __iter__(self):        return self    def __next__(self):        if self.index < len(self.data):            value = self.data[self.index]            self.index += 1            return value        else:            raise StopIteration# Example usagemy_object = MyIterable([1, 2, 3])for item in my_object:    print(item)
it appears that the _init_ (self,data)function has added a index value and set it to the integer 0, and added a data variable
It appears that the _iter_ (self)function merely returns itself to the calling function
it appears that the _next_(self) function (??????)

is it intended that each data structure created contains the index of the current element(row) and the total count of rows created? Do I need to keep track of these values within the main program? is there some other mechanism this code is interacting with of which I am unaware?

Statistics: Posted by ras_oscar — Mon Apr 21, 2025 10:33 pm



Viewing all articles
Browse latest Browse all 7314

Trending Articles