0% found this document useful (0 votes)
22 views

csv files

The document provides an overview of CSV files and their usage in Python, highlighting the built-in csv module for reading and writing operations. It includes practical examples for opening, writing, and reading CSV files, as well as activities for hands-on practice. Key points emphasize proper file management and the importance of understanding different csv functionalities.

Uploaded by

shivambhatt867
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

csv files

The document provides an overview of CSV files and their usage in Python, highlighting the built-in csv module for reading and writing operations. It includes practical examples for opening, writing, and reading CSV files, as well as activities for hands-on practice. Key points emphasize proper file management and the importance of understanding different csv functionalities.

Uploaded by

shivambhatt867
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Understanding CSV Files in

Python
LEARNING OBJECTIVES:TO LEARN AND
UNDERSTAND THE USAGE OF CSV FILES AND
APPLYING ITS OPERATIONS
Introduction to CSV Files
● CSV stands for Comma-Separated Values.
● It is a simple file format used to store tabular data.
● Commonly used for data exchange between applications.
What is the csv Module?
● Python has a built-in module called csv.
● It simplifies reading from and writing to CSV files.
● Essential for data manipulation tasks.
Importing the csv Module
● To use the csv module, you must import it.
● Use the command: `import csv`.
● This allows access to all csv functionalities.
Opening a CSV File
● Use the `open()` function to access CSV files.
● Always remember to close the file after use.
● Example: `file = open('students.csv', 'r')`.

● # Opening a CSV file


● file = open('students.csv', 'r')

● # Closing the CSV file


● file.close()
Using the with Statement
● The `with` statement automatically closes the file.
● It ensures proper resource management.
● Example: `with open('students.csv', 'r') as file:`.
Writing into a CSV File
● Use `csv.writer()` to write data.
● It allows writing single or multiple rows.
● Important for data storage tasks.

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


● writer = csv.writer(file)
Writing a Single Row
● Use `writerow()` to write a single row.
● Useful for adding headers or individual records.

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


● writer = csv.writer(file)
● writer.writerow(['Name', 'Age', 'Grade']) # Writing header row
● writer.writerow(['John', 18, 'A']) # Writing data row
Writing Multiple Rows
● Use `writerows()` to write multiple rows at once.
● Takes a list of lists as input.
● Example: `writer.writerows(rows)`.

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


● writer = csv.writer(file)
● rows = [['Name', 'Age', 'Grade'], ['John', 18, 'A'], ['Emma', 17,
'B']]
● writer.writerows(rows)
Reading from a CSV File
● Use `csv.reader()` to read data from CSV files.
● Reads line by line and returns lists for each row.
● Essential for data retrieval tasks.

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


● reader = csv.reader(file)
● for row in reader:
● print(row) # Each row is a list of values
Using csv.reader()
● Example: `for row in reader: print(row)`.
● Each row is represented as a list.
● Great for iterating through data.
Skipping the Header Row
● Use `next(reader)` to skip the header row.
● This is useful when processing data.
● Example: `for row in reader: print(row)`.

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


● reader = csv.reader(file)
● next(reader) # Skipping the header row
● for row in reader:
● print(row)
Example: Writing and Reading
● Demonstrates both writing and reading from a CSV file.
● Combines previous concepts into a single example.
● Helps solidify understanding of CSV operations.
Example: Writing and Reading
● import csv

● # Writing data to a CSV file


● with open('students.csv', 'w', newline='') as file:
● writer = csv.writer(file)
● writer.writerow(['Name', 'Age', 'Grade'])
● writer.writerows([['John', 18, 'A'], ['Emma', 17, 'B'], ['Alex', 19, 'A']])

● # Reading data from the CSV file


● with open('students.csv', 'r') as file:
● reader = csv.reader(file)
● next(reader) # Skipping the header row
● for row in reader:
● print(row)
Key Points to Remember
● Always close files after use.
● Use the `with` statement for better management.
● Understand the difference between `writerow()` and `writerows()`.

● Delimiter: The default delimiter in CSV is a comma (,), but you can specify other delimiters like
semicolons (;) or tabs (\t) using the delimiter parameter in csv.writer() or csv.reader().
● newline='': While writing to a CSV file, the newline='' argument in open() ensures no blank lines are
written between rows in certain environments.
Activity Question 1
● Create a CSV file named `employees.csv`.
● Store employee details: name, age, department.
● Use the csv module to accomplish this task.
Activity Question 1
import csv

# Writing data to employees.csv


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

# Writing the header row


writer.writerow(['Name', 'Age', 'Department'])

# Writing the employee details


writer.writerows([
['John Doe', 28, 'HR'],
['Jane Smith', 22, 'Finance'],
['Emily Davis', 32, 'IT'],
['Michael Brown', 26, 'Marketing']
])

print("Employee details have been written to employees.csv")


Activity Question 2
● Read the `employees.csv` file.
● Display employees whose age is greater than 25.
● Practice filtering data from CSV files.
Activity Question 2
import csv

# Reading data from employees.csv and filtering based on age


with open('employees.csv', 'r') as file:
reader = csv.reader(file)

print("Employees with age greater than 25:")

for row in reader:


name, age, department = row[0], row[1], row[2]

# Check if the age is greater than 25 and display the employee details
if age.isdigit() and int(age) > 25:
print(f"Name: {name}, Age: {age}, Department: {department}")
Activity Question 3
● Modify the previous program to skip the header row.
● This enhances your understanding of data processing.
● Focus on practical application of concepts learned.
Activity Question 3
import csv

# Reading data from employees.csv and filtering based on age, skipping the header
with open('employees.csv', 'r') as file:
reader = csv.reader(file)

# Skip the header row


next(reader)

print("Employees with age greater than 25:")

for row in reader:


name, age, department = row[0], row[1], row[2]

# Check if the age is greater than 25 and display the employee details
if age.isdigit() and int(age) > 25:
print(f"Name: {name}, Age: {age}, Department: {department}")
Wrap-Up and Questions
● What challenges did you face while working with CSV files?
● How can you apply this knowledge in real-world scenarios?
● Discuss your thoughts and experiences with the class.
Further Learning Resources
● Explore Python's official documentation on the csv module.
● Look for online tutorials and exercises.
● Practice by creating your own CSV files and manipulating data.
Conclusion
● CSV files are essential for data management.
● Python's csv module simplifies working with these files.
● Mastering these skills will enhance your programming
capabilities.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy