Home > front end >  avoid overwriting excel file and create a new name with pandas
avoid overwriting excel file and create a new name with pandas

Time:09-21

When I ask pandas to generate the excel file, is there any way for him to see the name already exists and create a new file like "dados_extraidos_1.xlsx"

if (imovel):
    df = pd.DataFrame(lista_imoveis, columns=['Bairro/Endereço','Valor Total','Metragem','Qtd Quartos','Vagas','Condomínio','Dados Adicionais','Link'])
    df.to_excel('dados_extraidos.xlsx', index=False)
else:
    print('Erro')

CodePudding user response:

You can check if that file exists already, and if so append a number to it: Instead of df.to_excel('dados_extraidos.xlsx', index=False) you'll have:

from pathlib import Path
from glob import glob
... # Your code

if (imovel):
   output_name = Path("dados_extraidos.xlsx")
   i = glob(output_name.stem   "_[0-9]*"   output_name.suffix)
   new_output_name = f"{output_name.stem}_{len(i)}{output_name.suffix}"
   df.to_excel(new_output_name, index=False)
...

CodePudding user response:

Here's a helper function to write a unique file. mode='x' opens for exclusive creation, and fails if the file already exists:

import pandas as pd
import os

def write_excel_unique(filename):
    base,ext = os.path.splitext(filename)
    count = 0
    while True:
        try:
            with pd.ExcelWriter(filename, mode='x') as file:
                df.to_excel(file, index=False)
        except FileExistsError:
            count  = 1
            filename = f'{base}_{count}{ext}'
        else:
            return filename
    
df = pd.DataFrame([[1,2],[3,4],[5,6]], columns=['Col1','Col2'])
actual = write_excel_unique('output.xlsx')
print('Wrote',actual)
actual = write_excel_unique('output.xlsx')
print('Wrote',actual)
actual = write_excel_unique('output.xlsx')
print('Wrote',actual)

Output:

Wrote output.xlsx
Wrote output_1.xlsx
Wrote output_2.xlsx
  • Related