How to import csv file in Python
Understanding CSV Files
Think of CSV (Comma Separated Values) files like a simplified spreadsheet stored as a plain text file. Each line in the CSV file corresponds to a row in the spreadsheet. Within a line, fields are separated by commas, each representing a cell in the spreadsheet.
Why Use CSV Files?
CSV files are simple and universal. They are easy to read and write from the code and can be opened with any text editor. This makes them a popular choice for data storage in many applications.
Getting Started with CSV in Python
Python provides a built-in module named 'csv' to work with CSV files. You can import this module into your code using the import
statement.
import csv
This line allows you to access all the functions and classes available in the csv
module.
Reading a CSV File
Let's start with reading a CSV file. Imagine a CSV file named 'students.csv' with the following content:
name,age,grade
John,12,7
Sally,13,7
Emma,14,9
Here's how you can read this file in Python:
import csv
with open('students.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Here, open
is a built-in Python function that opens a file. 'r'
stands for 'read mode', which means we're opening the file to read data from it. csv.reader
creates an object that reads lines from the file. The for
loop then iterates over each line, printing it to the console.
Understanding the Output
When you run the code, you'll see this output:
['name', 'age', 'grade']
['John', '12', '7']
['Sally', '13', '7']
['Emma', '14', '9']
What we get is a list of lists, where each inner list represents a row of the file.
Working with CSV Data
Once you've read the data from a CSV file, you can work with it just like any other data in Python. For example, you can access individual fields in a row using indexing.
import csv
with open('students.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print('Name: ', row[0], ', Age: ', row[1], ', Grade: ', row[2])
This code will output:
Name: name , Age: age , Grade: grade
Name: John , Age: 12 , Grade: 7
Name: Sally , Age: 13 , Grade: 7
Name: Emma , Age: 14 , Grade: 9
Writing to a CSV File
Writing to a CSV file is as simple as reading from it. Here's how you can write data to a CSV file:
import csv
data = [
['name', 'age', 'grade'],
['John', '12', '7'],
['Sally', '13', '7'],
['Emma', '14', '9']
]
with open('students.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
Here, 'w'
stands for 'write mode', which means we're opening the file to write data to it. writer.writerows
writes all the data rows to the file.
Dealing with CSV Headers
The first row of a CSV file often contains headers (field names). Python's csv
module provides a handy DictReader
class to read CSV files with headers. Here's how you can use it:
import csv
with open('students.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(row)
This code will output:
{'name': 'John', 'age': '12', 'grade': '7'}
{'name': 'Sally', 'age': '13', 'grade': '7'}
{'name': 'Emma', 'age': '14', 'grade': '9'}
As you can see, each row is now a dictionary that maps field names to field values. This makes it easier to work with CSV data, especially when it has many fields.
Conclusion
Learning to import CSV files in Python opens up a world of possibilities for working with data. Whether you're building a data analysis tool or a web application, understanding how to read and write CSV files is a great skill to have in your toolkit.
Think of CSV files as a box of Lego bricks. Each line or row is a unique piece that you can use to build a variety of structures, from simple data tables to complex machine learning models. With Python's csv
module, you have the tools you need to open the box and start building. So, go ahead and build something amazing!