Create temporary file and open it with pandas

0

I am trying to create a temporary excel and open it, to later delete it. With this, what I intend to do is to be able to consult an excel without having to save anything in memory.

My code is:

  def abrir(self):
    nombreFichero = "Temporal"+datetime.datetime.now().isoformat()+".xlsx"
    handle, fn = tempfile.mkstemp(suffix='.xlsx')
    self.writer = pd.ExcelWriter(nombreFichero, engine='openpyxl')
    self.df.toexcel(self.writer)

But I can not create the temporary file at any time ...

    
asked by Adriana_0_0 07.09.2018 в 10:49
source

1 answer

0

The file is created, but it does it in the default directory for temporary files, which depends on the operating system , for example /tmp in GNU / Linux ..

If you want to create a particular directory you must use the dir argument to indicate the route. In general it is preferable to use the default directory, this facilitates future cleaning, even the operating system is usually configured (although this depends on the specific system) to clean the temporary files automatically at restart, logoff, by time, etc. If you place the file in another directory you prevent the system from deleting the file if something could not be eliminated by the process. Keep in mind that a temporary file may not be deleted by the program that created it, either because it is not explicitly deleted or, what is more common, because there is an uncontrolled termination of the process that created it before it was created. I could eliminate it.

On the other hand, tempfile.mkstemp returns a tuple in which the first element is the file descriptor and the second the path to it, use this return to access the file.

import os
import tempfile
import pandas as pd

def abrir():
    prefix = f"Temporal{datetime.datetime.now().isoformat()}"
    fd, path = tempfile.mkstemp(prefix=prefix, suffix='.xlsx', dir=os.getcwd())
    writer = pd.ExcelWriter(path, engine='openpyxl')
    self.df.to_excel(writer, 'Sheet1')
    writer.save()
    writer.close()

To save the changes to the file you must call the save of self.writer method or better use with so that it is automatically responsible for saving and closing when finished. Note that unlike tempfile.NamedTemporaryFile or tempfile.TemporaryFile you are responsible for deleting the file manually when you finish, so do not forget to call os.remove(path) when you're done with it. The how it already depends on your specific case, usually we use a try - finally to make sure that the file is destroyed despite possible exceptions:

def abrir(self):
    prefix = f"Temporal{datetime.datetime.now().isoformat()}" 
    fd, path = tempfile.mkstemp(prefix=prefix, suffix='.xlsx', dir=os.getcwd())
    try:
        with pd.ExcelWriter(path, engine='openpyxl') as writer:
            self.df.to_excel(writer, 'Sheet1')

        # Resto de tareas con el archivo

    finally:
        os.remove(path)
    
answered by 07.09.2018 в 12:23