pythonwriter

Output an Excel file to a separate directory than the Python code, also name the file something other than the directory


I have a code that takes data from multiple modeling file, does some math with the data and outputs the data to Excel. I have the code take in all the files in the directory and creates a sheet per model in one Excel workbook. I have it set up so the outputted Excel file is in the directory of all the files and not the directory where the code belongs. The way I do this though makes the name of the Excel the name of the first model with a .xlsx at the end. Is there a way to specify the directory but also name the file something I choose? Here is an example of the code:

pythonfolder = C:User\Limit\PythonCodes
idir = r'C:User\Limit\ModelFiles'
    ipfiles = os.listdir(idir)
    ipfiles = [s for s in ipfiles if bool(re.search('.\.sosat', s))]

    opf = "excelfile.xlsx"
    dflist = list()
    for fi in ipfiles:
        ipf = idir + '\\' + fi
        opf = idir + '\\' + re.sub('\.sosat', '.xlsx', fi)
        df = SMA_finder(ipf, opf, fi)
        dflist.append(df)
        npf = ipfiles
    with pd.ExcelWriter(opf) as writer:
         for i in range(len(dflist)):
                sheetname = npf[i]
                dflist[i].to_excel(writer, sheet_name=sheetname)

I cannot add more code due to the sensitivity of the information, but the code will either write the Excel file with a name matching the first file or if I change opf in pd.ExcelWriter(opf), the Excel file will be created in the folder the code is in. I know this one can be a little tricky to answer with the lack of supporting code but any help or ideas are appreciated.


Solution

  • Surely it's just:

    opf = idir + '\\yourfilename.xlsx'
    

    Or from a variable (and using f-strings assuming Python 3.6 or better):

    full_output_filename = f'{idir}\\{output_filename}.xlsx'