Python Forum

Full Version: Appending a row of data in an MS Excel file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the following working code which amalgamates excel file data into one Excel file. How do I amend the code so that I do not have an index column on the first column?

import pandas as pd
import os

input_location = "D:/Power BI & Python/Test - Input File/"
output_location = "D:/Power BI & Python/Test - Output File/"
output_file = "Consolidated.xlsx"

excelfiles = os.listdir(input_location)

excelfilesdf = pd.DataFrame()

for excelfile in excelfiles:
    if excelfile.endswith('xlsx'):
        dfFilename = {'sales_id':excelfile}  # to place the MS Excel filename in the first column, use the first column header
        df = pd.read_excel(input_location + excelfile)
        excelfilesdf = excelfilesdf.append(dfFilename, ignore_index=True)
        excelfilesdf = excelfilesdf.append(df)

excelfilesdf.to_excel(output_location + output_file)
Read the documentation for DataFrame.to_excel(). There is an argument that controls if the row index names are written to the file.

While you're at it you should take a look at glob. Would be useful for what you are doing (finding all files with extension .xlsx).

https://docs.python.org/3/library/glob.html
(Nov-05-2022, 08:27 PM)azizrasul Wrote: [ -> ]How do I amend the code so that I do not have an index column on the first column?
Like this.
excelfilesdf.to_excel(output_location + output_file, index=False)
Thanks both. I was using index=False but unfortunately in the wrong line, that's why it gave me an error.