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

Python • Re: making a data object iterable

$
0
0
I've finally gotten the routine to a place where it does what i wanted it to. I have also learned a great deal.Thanks to all the generous members that helped me out. I have posted the code below along with a quick description in the event someone stumble across this thread in the future looking for the same answers.

Code:

#this routine explores the use of the CSV read and write functions.#write 2 or more csv files in any convenient directory#the routine will request the directory and take a listing of the file names#open each file sequentially, add a date and write the lines it out to a new consolidated file# limitations: the routine does not check to see that the files are CSVs.#if you feed it something else the results are unknownimport csvfrom datetime import dateimport tkinter as TKfrom tkinter import filedialogimport osclass order:    NUM_ELEMENTS = 4    def __init__(self, line_in ):        self.Name = line_in[0]        self.DOB = line_in[1]        self.POB = line_in[2]        self.OrderNo = line_in[3]        self.Date = date.today()        self.index = 0            def __iter__(self):        self.index = 0        return self              def __next__(self):        if self.index > order.NUM_ELEMENTS:            raise StopIteration        else:            try:                if self.index == 0: return self.Name                if self.index == 1: return self.DOB                if self.index == 2: return self.POB                if self.index == 3: return self.OrderNo                if self.index == 4: return self.Date            finally:                self.index += 1                directory = filedialog.askdirectory()files = os.listdir(directory)with open(directory + '/Consolidated.csv','a')as outfile:    writer = csv.writer(outfile)     for file in files:        with open(directory + '/' + file, 'r') as infile:            reader = csv.reader(infile)                           for row in reader:                lorder = order(row)                writer.writerow(lorder)outfile.close()infile.close()

Statistics: Posted by ras_oscar — Sat Apr 26, 2025 2:52 am



Viewing all articles
Browse latest Browse all 1361

Trending Articles