Appending Data to Excel File using Pandas in Python - No Overwriting

If you are using Pandas in Python to work with Excel files, you may come across the need to append data to an existing Excel file without overwriting the existing data. This can be achieved easily by using the Pandas append() function along with the openpyxl library.

├Źndice
  1. Step 1: Import the Required Libraries
  2. Step 2: Check if the Excel File Exists
  3. Step 3: Read the Existing Data
  4. Step 4: Append the New Data
  5. Step 5: Write the Data to the Excel File

Step 1: Import the Required Libraries

Before we start appending data, we need to import the necessary libraries. We will be using Pandas, openpyxl, and os libraries for this purpose.

<pre><code>import pandas as pd
import openpyxl
import os</code></pre>

Step 2: Check if the Excel File Exists

Before we append data to an existing Excel file, we need to check if the file exists. If it does not exist, we can create a new file and add data to it. If it exists, we can append the data to it. We can use the os library to check if the file exists.

<pre><code>if os.path.isfile('file.xlsx'):
    book = openpyxl.load_workbook('file.xlsx')
    writer = pd.ExcelWriter('file.xlsx', engine='openpyxl') 
    writer.book = book
else:
    writer = pd.ExcelWriter('file.xlsx', engine='openpyxl')

Step 3: Read the Existing Data

After we check if the Excel file exists, we need to read the existing data from the file. We can use the Pandas read_excel() function for this purpose.

<pre><code>reader = pd.read_excel('file.xlsx')

Step 4: Append the New Data

Now that we have read the existing data, we can append the new data to it using the Pandas append() function.

<pre><code>new_data = pd.DataFrame({'Column1': [1, 2, 3],
                             'Column2': [4, 5, 6]})
df = reader.append(new_data, ignore_index=True)

Step 5: Write the Data to the Excel File

Finally, we need to write the data to the Excel file using the Pandas to_excel() function.

<pre><code>df.to_excel(writer, sheet_name='Sheet1', index=False)
writer.save()

With these five simple steps, we can append data to an existing Excel file without overwriting the existing data using Pandas in Python.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information