Welcome to the CSV Files lesson in Python! Today, we'll learn how to work with CSV (Comma Separated Values) files, which are a common data format used for exchanging data between applications. š
CSV files are simple text files that store data in tabular format, with each line representing a row and columns separated by commas. Here's an example of a simple CSV file:
Name,Age,Occupation
Alice,30,Developer
Bob,25,Designer
Charlie,35,Manager
To read a CSV file in Python, we use the pandas library, which provides a powerful data manipulation toolkit. If you haven't installed pandas, you can do so using pip:
pip install pandasNow, let's read the CSV file we created earlier:
import pandas as pd
data = pd.read_csv('data.csv')
print(data)This will output:
Name Age Occupation
0 Alice 30 Developer
1 Bob 25 Designer
2 Charlie 35 Manager
š” Pro Tip: Save your CSV file as 'data.csv' in the same directory as your Python script for this example to work correctly.
To write data to a CSV file, we can use the to_csv method:
data.to_csv('output.csv', index=False)This will create a new CSV file named 'output.csv' with the data from the data variable. The index=False argument ensures that row indices are not written to the file.
With pandas, we can perform various operations on CSV files, such as filtering, sorting, and manipulating data. Here's an example of filtering the data based on the Occupation column:
developers = data[data['Occupation'] == 'Developer']
print(developers)This will output:
Name Age Occupation
0 Alice 30 Developer
Which Python library do we use to read and write CSV files?
By now, you should have a solid understanding of how to work with CSV files in Python. As you progress in your Python journey, you'll find CSV files to be a versatile and convenient data storage format for various applications. š” Happy Coding!