Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

CSV File Handling

This document discusses handling CSV files in Python. It covers reading from and writing to CSV files using the csv module, including reading into dictionaries and writing from dictionaries. It also covers best practices like using context managers and handling errors, as well as manipulating CSV data and advanced topics. Exercises are provided to practice these skills, such as reading data and calculating statistics to write to a new CSV file.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

CSV File Handling

This document discusses handling CSV files in Python. It covers reading from and writing to CSV files using the csv module, including reading into dictionaries and writing from dictionaries. It also covers best practices like using context managers and handling errors, as well as manipulating CSV data and advanced topics. Exercises are provided to practice these skills, such as reading data and calculating statistics to write to a new CSV file.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Learning Notes: CSV File Handling in Python with Examples

**1. Introduction to CSV Files:**


- CSV stands for Comma Seperated Values
- CSV (Comma Separated Values) files are a popular file format for storing tabular data.
- Each line of the file represents a row, and the values within each row are separated by commas.

**2. Reading CSV Files:**


- Use the `csv.reader` class to read a CSV file.

```python
import csv

with open('data.csv', 'r') as file:


reader = csv.reader(file)
for row in reader:
print(row)
```

**3. Reading CSV Files with Headers:**


- When the CSV file has headers, skip the first row using `next(reader)`.

```python
with open('data.csv', 'r') as file:
reader = csv.reader(file)
header = next(reader)
for row in reader:
print(row)
```

**4. Writing to CSV Files:**


- Use `csv.writer` to create and write data to a CSV file.

```python
import csv

with open('output.csv', 'w', newline='') as file:


writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 25, 'New York'])
writer.writerow(['Bob', 30, 'San Francisco'])
```

**5. Reading CSV Files into Dictionaries:**


- Use `csv.DictReader` to read CSV files into dictionaries.

```python
with open('data.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(row['Name'], row['Age'], row['City'])
```

**6. Writing CSV Files from Dictionaries:**


- Use `csv.DictWriter` to write CSV files from dictionaries.

```python
data = [{'Name': 'Alice', 'Age': 25, 'City': 'New York'},
{'Name': 'Bob', 'Age': 30, 'City': 'San Francisco'}]

with open('output.csv', 'w', newline='') as file:


fieldnames = ['Name', 'Age', 'City']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
```

**7. CSV File Manipulation:**


- After reading a CSV file, you can manipulate the data using Python.
- Example: Calculate the average age of individuals in a CSV file.

**8. Error Handling:**


- Handle errors gracefully, such as checking for file existence or handling exceptions when reading or writing

```python
try:
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
except FileNotFoundError:
print("File not found.")
```

**9. Best Practices:**


- Use context managers (`with` statements) for proper file handling, ensuring that files are properly closed.
- Handle exceptions when working with files.

**10. Advanced Topics:**


- Advanced topics include handling CSV files with different delimiters, handling missing data, and dealing with

**11. Exercises:**
- Practice reading CSV files, performing data analysis or manipulation, and writing the results back to a new

**12. Additional Resources:**


- Explore the Python `csv` module documentation for more advanced features.
- Consider using libraries like pandas for more powerful data analysis capabilities.

**Exercises:**

1. Read a CSV file containing student names and grades. Calculate the average grade and write it to a new CSV file

2. Read a CSV file with sales data, calculate the total sales, and write it to a new CSV file with a summary.

3. Read a CSV file containing employee data. Find the youngest and oldest employees and write their details to a

4. Handle a CSV file with a different delimiter (e.g., tab or semicolon) and read/write it using the appropriate

**Assessment:**
- Students can be assessed based on their ability to read, write, and manipulate CSV files using Python, as well

Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/fontdata.js

You might also like