Read and Write data from excel and csv from python

In python we can read data from different sources using pandas library in few line of code. Pandas is a open source mostly used data analysis library which support to read data from multiple sources and transforming data as per analysis requirement. here we discuss how to read and save excel and csv data in python.

Import the required libraries:

import pandas as pd

This line imports the pandas library and assigns it the alias pd, which is a commonly used convention.

Read the CSV file using python libraries

df = pd.read_csv('filename.csv')
df

Here, the read_csv() function from pandas is used to read the contents of a CSV file named 'filename.csv' into a DataFrame. The DataFrame is assigned to the variable df.

By simply typing df in the code, the DataFrame’s contents will be displayed in the output. This step is optional and can be used to inspect the data or verify the read operation.

Save the modified DataFrame to a new CSV file:

New_df.to_csv('filename.csv', index=False)

This line saves the modified DataFrame (assuming there is a DataFrame named New_df) to a new CSV file named 'filename.csv'.

The to_csv() function is called on the DataFrame object (New_df) and is provided with the file name and extension as the argument.

Set index=False to exclude row indices in the saved file.

Similarly, we can read excel file

import pandas as pd
# Read excel file
df= pd.read_excel('filename.xlsx')
df
# Save file in excel.
New_df.to_excel('filename.xlsx',index=False)

Please follow and like us:
error
fb-share-icon

Leave a Comment

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

Scroll to Top