avoid overwriting excel file and create a new name with pandas

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')

Answer

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)
...