Working with csv files in Python
×


Working with csv files in Python

123

Working with CSV Files in Python

Introduction to CSV Files

CSV (Comma-Separated Values) files are a straightforward and widely used format for storing tabular data. Each line in a CSV file represents a record, and fields within records are separated by commas. This simplicity makes CSV files ideal for data exchange between different applications.

Reading CSV Files in Python

Python's built-in csv module provides functionality to read CSV files. Here's how you can read a CSV file and print its content:

import csv

with open('data.csv', mode='r') as file:
    csv_reader = csv.reader(file)
    for row in csv_reader:
        print(row)

This code opens the 'data.csv' file in read mode, creates a CSV reader object, and iterates through each row, printing it to the console.

Reading CSV Files into a Dictionary

To read CSV files into a dictionary format, where the keys are the column headers, you can use the csv.DictReader class:

import csv

with open('data.csv', mode='r') as file:
    csv_dict_reader = csv.DictReader(file)
    for row in csv_dict_reader:
        print(row)

This approach is useful when you want to access data by column names rather than by index.

Writing to CSV Files

Writing data to a CSV file can be done using the csv.writer class. Here's an example:

import csv

header = ['Name', 'Age', 'City']
rows = [['Alice', 30, 'New York'], ['Bob', 25, 'Los Angeles']]

with open('output.csv', mode='w', newline='') as file:
    csv_writer = csv.writer(file)
    csv_writer.writerow(header)
    csv_writer.writerows(rows)

This code writes a header row followed by multiple data rows to the 'output.csv' file.

Writing Dictionaries to CSV Files

If you have data in dictionary format and want to write it to a CSV file, you can use the csv.DictWriter class:

import csv

header = ['Name', 'Age', 'City']
rows = [{'Name': 'Alice', 'Age': 30, 'City': 'New York'}, {'Name': 'Bob', 'Age': 25, 'City': 'Los Angeles'}]

with open('output_dict.csv', mode='w', newline='') as file:
    csv_dict_writer = csv.DictWriter(file, fieldnames=header)
    csv_dict_writer.writeheader()
    csv_dict_writer.writerows(rows)

This method is particularly useful when working with data stored in dictionaries.

Handling CSV Files with Pandas

For more advanced operations, the pandas library offers powerful tools to work with CSV files. To read a CSV file into a DataFrame:

import pandas as pd

df = pd.read_csv('data.csv')
print(df)

To write a DataFrame to a CSV file:

df.to_csv('output_pandas.csv', index=False)

Pandas provides a wealth of functionality for data manipulation and analysis, making it a popular choice for working with CSV files.

Storing Emails in CSV Files

You can also store email addresses in a CSV file. Here's an example:

import csv

header = ['Name', 'Email']
rows = [['Alice', 'alice@example.com'], ['Bob', 'bob@example.com']]

with open('emails.csv', mode='w', newline='') as file:
    csv_writer = csv.writer(file)
    csv_writer.writerow(header)
    csv_writer.writerows(rows)

This code creates a CSV file 'emails.csv' with names and email addresses.

Conclusion

Working with CSV files in Python is straightforward, thanks to the built-in csv module and the powerful pandas library. Whether you're reading data into lists, dictionaries, or DataFrames, Python provides the tools you need to handle CSV files efficiently.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat