(Nov-08-2022, 07:28 AM)JonWayn Wrote: With this arrangement, CreateFile doesn't have a return line and the caller then gets nothing to do its function with. I think if it returns f, the file will close as soon as the function ends so I'm not sure what the caller gets. I will set up a test for itYes,but the first code just open a diffent file object and return it this make no sense at all.
So i can write a more flexible apporch using a class and some gussing what this task shall do.
# court.py import csv import os class Court: def __init__(self, filepath, filename, fullpath=''): self.filepath = filepath self.filename = filename self.fullpath = os.path.join(self.filepath, self.filename) def check_path(self): if not os.path.exists(self.fullpath): # Folder dos not exists,make it os.makedirs(self.filepath) self.fullpath = os.path.join(self.filepath, self.filename) else: # The folder/file exists self.fullpath def create_file(self): header = ['Court', 'Location', 'Citation Number', 'Case Description', 'File Date', ] with open(self.fullpath, 'a', encoding='utf-8', newline='') as f: writer = csv.writer(f) writer.writerow(header) def add_to_csv(self, data): with open(self.fullpath, mode='a', newline='') as cv: writer = csv.writer(cv, delimiter=',', quoting=csv.QUOTE_MINIMAL) writer.writerow(data) @property def read_csv(self): with open(self.fullpath, newline='') as csv_file: reader = csv.reader(csv_file) for row in reader: print(', '.join(row))Using this class,no folder of file exsist when i start this.
λ ptpython -i court.py >>> obj = Court(r'G:\div_code\test_cs1', 'data.csv') >>> obj.check_path() >>> obj.create_file() # Now can read to see what have so far >>> obj.read_csv Court, Location, Citation Number, Case Description, File Date # Add data to csv >>> cort_data = ['Kent', 'Usa', '44455', 'Theft of car dealer', '8-11-22'] >>> obj.add_to_csv(cort_data) >>> cort_data = ['Murder', 'Norway','9999', 'Bank robber', '5-1-22'] >>> obj.add_to_csv(cort_data) # Read again to see what have now >>> obj.read_csv Court, Location, Citation Number, Case Description, File Date Kent, Usa, 44455, Theft of car dealer, 8-11-22 Murder, Norway, 9999, Bank robber, 5-1-22If look this hope see that this is more flexible,and is now easy to change if have more Court data(can just loop over and add).