How do I return a record recently added within the same function?

46 Views Asked by At

I am using pandas excelwriter to add records to an excel file and am attempting to gain confirmation of the record being added upon completion.

def add_mem(self, fn, ln, stadd, city, zip):
    __new_index = int(self.find_memend()) + 3
    new_mem_dict = pd.DataFrame({"Member_ID" : [int(__new_index)],
                                      "Fname" : [fn],
                                      "Lname" : [ln],
                                      "Street_Add" : [stadd],
                                      "City" : [city],
                                      "Zip" : [zip]})
    new_mem_dict = new_mem_dict.set_index("Member_ID")
    new_mem_dict['Zip'] = new_mem_dict['Zip'].str.pad(width = 5, fillchar='0')
    with pd.ExcelWriter(self.excel_file, mode = 'a', if_sheet_exists='overlay') as writer:
        new_mem_dict.to_excel(writer, sheet_name='Members', startrow=writer.sheets['Members'].max_row, header=False)
    _members_added = (self.find_memend())
    _newmem = self.search_memID(_members_added)
    return print('{}\nwas added to database'.format(_newmem))

Currently this is just a test code until I get all the functionality I want. As you can see, I generate a new index for the record then create a the dataframe for the record. I then add the record to an existing excel db. Finally, I check the the last record added. This is where things get screwy. The record that populates is the record prior to the new record.

I suspected that the file wasn't closing correctly, so I tried adding a close statement.

def add_mem(self, fn, ln, stadd, city, zip):
    __new_index = int(self.find_memend()) + 3
    new_mem_dict = pd.DataFrame({"Member_ID" : [int(__new_index)],
                                      "Fname" : [fn],
                                      "Lname" : [ln],
                                      "Street_Add" : [stadd],
                                      "City" : [city],
                                      "Zip" : [zip]})
    new_mem_dict = new_mem_dict.set_index("Member_ID")
    new_mem_dict['Zip'] = new_mem_dict['Zip'].str.pad(width = 5, fillchar='0')
    with pd.ExcelWriter(self.excel_file, mode = 'a', if_sheet_exists='overlay') as writer:
        new_mem_dict.to_excel(writer, sheet_name='Members', startrow=writer.sheets['Members'].max_row, header=False)
        writer.close()
    _members_added = (self.find_memend())
    _newmem = self.search_memID(_members_added)
    return print('{}\nwas added to database'.format(_newmem))

However this created an 'ValueError: I/O operation on closed file.'

Traceback (most recent call last):
  File "c:\Users\Mike\OneDrive\Documents\Apprenticeship Files\Python project\Library_Mods.py", line 156, in <module>
    Lib_Members().add_mem("Alexis", "Griffin", "470 Washington Avenue",
  File "c:\Users\Mike\OneDrive\Documents\Apprenticeship Files\Python project\Library_Mods.py", line 133, in add_mem
    with pd.ExcelWriter(self.excel_file, mode = 'a', if_sheet_exists='overlay') as writer:
  File "C:\Users\Mike\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\io\excel\_base.py", line 1322, in __exit__
    self.close()
  File "C:\Users\Mike\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\io\excel\_base.py", line 1326, in close
    self._save()
  File "C:\Users\Mike\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\io\excel\_openpyxl.py", line 109, in _save
    self.book.save(self._handles.handle)
  File "C:\Users\Mike\AppData\Local\Programs\Python\Python311\Lib\site-packages\openpyxl\workbook\workbook.py", line 386, in save
    save_workbook(self, filename)
  File "C:\Users\Mike\AppData\Local\Programs\Python\Python311\Lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
    archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Mike\AppData\Local\Programs\Python\Python311\Lib\zipfile.py", line 1305, in __init__
    self.start_dir = self.fp.tell()
                     ^^^^^^^^^^^^^^
ValueError: I/O operation on closed file

But when I try to locate the record using the same 'search_memID' function independently of this function, the record is located. So, now I am stuck on what to try next. Thank you any help.

0

There are 0 best solutions below