To delete data from an Excel file using Python, you can use the pandas
library. Here’s a sample code to delete data from an Excel file
import pandas as pd # Read the Excel file excel_file = 'path/to/your/excel/file.xlsx' df = pd.read_excel(excel_file) # Delete the data # Replace 'column_name' with the actual column name and 'condition_value' with the desired condition df = df[df['column_name'] != 'condition_value'] # Save the updated data to a new Excel file output_file = 'path/to/your/output/file.xlsx' df.to_excel(output_file, index=False) print("Data deleted successfully!")
In the code above, replace 'path/to/your/excel/file.xlsx'
with the actual path to your Excel file. You also need to replace 'column_name'
with the actual column name you want to use for the deletion condition and 'condition_value'
with the desired condition to identify the rows to be deleted. Finally, replace 'path/to/your/output/file.xlsx'
with the desired path to the output file.
The code uses the pandas
library to read the Excel file into a DataFrame using the pd.read_excel()
function.
It then deletes the data from the DataFrame based on the specified condition using boolean indexing.
Finally, the updated DataFrame is saved to a new Excel file using the to_excel()
function.
Make sure to have the pandas
library installed. You can install it using pip:
pip install pandas
Remember to handle any exceptions that may occur during file reading, data deletion, or file writing for proper error handling.