CSV (Comma-Separated Values) files are widely used for storing tabular data such as spreadsheets and databases in a simple, human-readable format. These files use commas to separate values and are supported by many applications including Microsoft Excel, Google Sheets, and most database software.
In Python, CSV files are handled efficiently using the built-in csv module. In addition, third-party libraries like pandas offer powerful tools for advanced CSV manipulation. This document provides an in-depth look at reading, writing, and processing CSV files in Python, with detailed examples and best practices.
A CSV file consists of rows and columns of data. Each line in the file represents a single row, and values are separated by commas (or other delimiters like semicolons or tabs).
Name, Age, City
Alice, 30, New York
Bob, 25, Los Angeles
Charlie, 35, Chicago
import csv
The csv.reader() function returns a reader object which can be iterated over to read lines in a CSV file.
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Often, CSV files include a header row. You can skip the header using next().
with open('data.csv', 'r') as file:
reader = csv.reader(file)
header = next(reader) # Skip header
for row in reader:
print(row)
You can specify a different delimiter (e.g., semicolon) using the delimiter parameter.
with open('semicolon_data.csv', 'r') as file:
reader = csv.reader(file, delimiter=';')
for row in reader:
print(row)
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 30, 'New York'])
data = [
['Name', 'Age', 'City'],
['Bob', 25, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
DictReader reads CSV data into a dictionary where keys are from the header row.
with open('data.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(row['Name'], row['Age'])
DictWriter writes dictionaries to a CSV file using specified fieldnames.
data = [
{'Name': 'Alice', 'Age': 30, 'City': 'New York'},
{'Name': 'Bob', 'Age': 25, 'City': 'Los Angeles'}
]
with open('output.csv', 'w', newline='') as file:
fieldnames = ['Name', 'Age', 'City']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
To append data without overwriting existing content, use mode 'a'.
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(['David', 40, 'Miami'])
with open('data.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
if int(row['Age']) > 30:
print(row)
import csv
with open('data.csv', 'r') as file:
reader = list(csv.DictReader(file))
sorted_data = sorted(reader, key=lambda x: int(x['Age']))
for row in sorted_data:
print(row)
with open('data.csv', 'r') as file:
rows = list(csv.DictReader(file))
for row in rows:
if row['Name'] == 'Alice':
row['Age'] = '31'
with open('data.csv', 'w', newline='') as file:
fieldnames = rows[0].keys()
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
pandas is a powerful data analysis library in Python. It provides built-in functions for reading and writing CSV files in a tabular format.
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
df.to_csv('output.csv', index=False)
filtered_df = df[df['Age'] > 30]
print(filtered_df)
sorted_df = df.sort_values('Age')
print(sorted_df)
For CSV files with tabs or semicolons:
reader = csv.reader(file, delimiter=';')
df = pd.read_csv('data.tsv', delimiter='\t')
writer = csv.writer(file, quoting=csv.QUOTE_ALL)
Handle encoding using the encoding parameter:
with open('data.csv', 'r', encoding='utf-8') as file:
reader = csv.reader(file)
try:
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
except FileNotFoundError:
print("File not found.")
Always use with for proper file closing and error handling.
CSV files are often used to store user registration or login info for small-scale applications.
Automated scripts often generate CSV reports for analysis.
Many datasets for ML come in CSV format and are loaded using pandas.
CSV logs are analyzed to monitor system behavior or user activity.
Working with CSV files in Python is a fundamental skill for developers, analysts, and data scientists. Python's built-in csv module makes it easy to handle structured data, while third-party tools like pandas add advanced capabilities for data analysis and transformation.
Whether you're storing logs, processing spreadsheets, or analyzing big datasets, knowing how to read, write, filter, and modify CSV files effectively is an essential part of Python programming. With the knowledge gained from this guide, you should be well-equipped to tackle real-world tasks involving CSV file manipulation.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved