How to read and write CSV in Python

Python is a powerful and versatile programming language, widely used for data analysis, machine learning, and other data-related tasks. One of the most common formats for storing and sharing data is the Comma Separated Values (CSV) file format. In this article, we will learn how to read and write CSV files in Python.

Reading CSV files in Python

To read a CSV file in Python, we need to use the csv module, which provides a simple and efficient way to work with CSV files. Here's a simple example of how to read a CSV file using Python:

                    
                        import csv

                        with open('data.csv', 'r') as f:
                            reader = csv.reader(f)
                            for row in reader:
                                print(row)
                    
                

In this example, we first import the csv module. We then open the file data.csv in read mode using the open() function. We then create a csv.reader object, which allows us to iterate over the rows in the CSV file. Finally, we loop over each row in the CSV file and print it.

Writing CSV files in Python

To write a CSV file in Python, we again use the csv module. Here's a simple example of how to write a CSV file using Python:

                    
                        import csv

                        data = [
                            ['Name', 'Age', 'City'],
                            ['John', 25, 'New York'],
                            ['Jane', 30, 'Chicago'],
                            ['Bob', 35, 'San Francisco']
                        ]

                        with open('data.csv', 'w', newline='') as f:
                            writer = csv.writer(f)
                            writer.writerows(data)
                    
                

In this example, we first define the data that we want to write to the CSV file as a list of lists. Each inner list represents a row in the CSV file. We then open the file data.csv in write mode using the open() function. We also pass the argument newline='' to the open() function to ensure that the CSV file is written correctly. We then create a csv.writer object, which allows us to write the rows to the CSV file. Finally, we call the writerows() method on the csv.writer object to write the data to the CSV file.

Conclusion

In this article, we learned how to read and write CSV files in Python using the csv module. Reading and writing CSV files is an essential task in data analysis and other data-related tasks. With the csv module in Python, working with CSV files becomes a simple and efficient task.