Python Tutorial: CSV Read/Write 📝

beginner
15 min

Python Tutorial: CSV Read/Write 📝

Welcome to CodeYourCraft's Python Tutorial on CSV Read/Write! This lesson is designed to help you understand and work with CSV files using Python, a powerful and versatile programming language. Let's dive in!

What are CSV Files? 💡

CSV (Comma Separated Values) files are simple data files that use commas to separate values and newline characters to separate lines. They are widely used for data storage and exchange because of their simplicity and universal support.

Reading a CSV File 🎯

To read a CSV file in Python, we use the built-in csv module. Here's an example of reading a CSV file and printing its content:

python
import csv with open('example.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)

In this example, replace 'example.csv' with the name of your CSV file. The csv.reader function reads the CSV file line by line, and each line is stored in the row variable.

Writing a CSV File 📝

Writing to a CSV file is just as simple. Let's create a new CSV file and write some data to it:

python
import csv data = [['Name', 'Age', 'City'], ['Alice', '25', 'New York'], ['Bob', '30', 'Chicago']] with open('output.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerows(data)

In this example, we first create a list of lists containing our data. Then, we open a new file output.csv in write mode and use the csv.writer function to write the data to the file.

Pro Tips 💡

  • Always ensure that your CSV file has a header row, even if it's empty. This helps when reading the CSV file, as you'll know what each column represents.
  • If you're dealing with a large CSV file, consider using the csv.DictReader and csv.DictWriter classes. They allow you to read and write CSV files using dictionaries, which can make your code more readable and easier to manage.

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the `csv` module in Python?


That's it for this lesson! With this knowledge, you can now work with CSV files in your Python projects. Happy coding! 🤖