csv files
csv files
csv files
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')`.
● 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
# 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)
# 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.