Using NamedTemporaryFile with Context Manager

51 Views Asked by At

I created a function to move tabular data from zipped outlook attachments to a dictionary object that contains the contents of all the respective data in a pandas dataframe, with the key being the file name and the date it was received.

Unfortunately, I'm finding that the only way for this script to work is to pass delete=False to the TempFile object. If I remove it, I get the following Microsoft error: "4096, 'Microsoft Outlook', 'Cannot save the attachment.'"

This kind of defeats the purpose of using the tempfile because the file remains on the disk. Can anyone tell me what I'm doing wrong with the tempfile object? Ideally, the file would get deleted after close. Wondering if it might be better to just use SpooledTemporaryFile instead, as the contents are being extracted to a temp directory anyways.

def df_attchs(attachment):
    df_objects={}
    with tempfile.TemporaryDirectory() as tdir:
        with tempfile.NamedTemporaryFile(delete=False) as tmp:
            attachment.SaveAsFile(tmp.name)
            with zipfile.ZipFile(tmp,'r') as zf:
                namelist=zf.namelist()
                infolist=zf.infolist()
                zf.extractall(tdir)
                root,dirs,files = next(os.walk(tdir,topdown=True))
                filepaths=[os.path.join(root, f) for f in files]
                for filepath in filepaths:
                    filename = os.path.basename(filepath)
                    filedate=infolist[namelist.index(filename)].date_time
                    key = (f'file: {filename} RecievedOn: {"/".join(map(str, filedate[:3]))}')
                    df_objects.update({key:to_pandas_df(filepath)})
    return df_objects
0

There are 0 best solutions below