Handling comma-separated values (CSV) files is a common task for many Python developers
CSV files are often used for data exchange between different systems, and it is critical to be able to handle them correctly.
One of the problems that developers often face when working with CSV files is how to deal with a comma within a field. In this tutorial, we will demonstrate how to handle the comma in CSV files in Python.
Steps:
1. Import the csv module:
The csv module is a built-in module in Python that provides functionality to work with CSV files. To start working with the csv module, we need to import it first using the following code:
1 |
import csv |
2. Open the CSV file:
Once we have imported the csv module, we need to open the CSV file. We can use the built-in open()
function to open the CSV file. In this example, we are opening a file named data.csv
located in the current directory:
1 2 3 4 5 6 |
with open('data.csv', 'r') as file: csv_reader = csv.reader(file) for row in csv_reader: print(row) |
3. Use the csv module’s reader
function to read the CSV file:
Now that we have opened the CSV file, we can use the csv module’s reader
function to read the CSV file. The reader
function returns an iterator that produces strings that represent the rows read from the CSV file. We can then loop through the iterator to access each row in the CSV file. In this example, we are printing each row in the CSV file:
1 2 3 4 |
with open('data.csv', 'r') as file: csv_reader = csv.reader(file) for row in csv_reader: print(row) |
4. Use the csv module’s writer
function to write the CSV file:
We can also use the csv module’s writer
function to write to a CSV file. The writer
function takes an iterable of rows and writes them to a CSV file. In this example, we are writing a list of tuples to a CSV file named data.csv
:
1 2 3 4 5 6 7 |
with open('data.csv', 'w', newline='') as file: csv_writer = csv.writer(file) csv_writer.writerows(data) |
Conclusion:
Handling commas in CSV files is a common problem that can be solved easily using the csv module in Python. We can read and write CSV files using the csv module’s reader
and writer
functions.
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import csv # Reading the CSV file with open('data.csv', 'r') as file: csv_reader = csv.reader(file) for row in csv_reader: print(row) # Writing to the CSV file with open('data.csv', 'w', newline='') as file: csv_writer = csv.writer(file) csv_writer.writerows(data) |
Output:
['John', 'Doe', '[email protected]', 'New York, NY'] ['Jane', 'Doe', '[email protected]', 'San Francisco, CA'] ['Bob', 'Smith', '[email protected]', 'Los Angeles, CA']
This is how the csv file looks inside Excel: