In this tutorial, we will learn how to write a new line in a CSV file using Python. We will use the built-in csv module, which provides functionality to read from and write to CSV files. This tutorial assumes that you have basic knowledge of Python and a bit of familiarity with working with CSV data.
Step 1: Import the CSV Module
The first thing you need to do is import the csv module. This module is included in Python’s standard library, and there is no need to install any additional packages. To import the csv module, use the following code:
1 |
import csv |
Step 2: Create and Open a CSV File for Writing
Next, we need to create a new CSV file or open an existing one for writing. We will use the built-in open() function to do this. The open() function accepts two parameters: the file name with its path and the file mode. In this case, we will use the mode ‘w’ for writing. Make sure to use the newline=” parameter to properly handle newlines in the CSV file.
1 |
csv_file = open('example.csv', 'w', newline='') |
Step 3: Create a CSV Writer
Once we have the file open for writing, we will create a CSV writer. The CSV writer is an object that is used to write CSV data into a given file using the csv.writer() function. It accepts the file object as its parameter.
1 |
csv_writer = csv.writer(csv_file) |
Step 4: Write Rows to the CSV File
Now that we have the CSV writer, we can use its writerow() method to write individual rows to the CSV file. Each row should be a list of values. To write a new line in a CSV file, simply write another row.
1 2 3 |
csv_writer.writerow(['Name', 'Age', 'City']) csv_writer.writerow(['Alice', '24', 'New York']) csv_writer.writerow(['Bob', '30', 'San Francisco']) |
Step 5: Close the CSV File
After writing all the rows, it is essential to close the file using the close() method of the file object. This will ensure that all the data has been properly written to the file and that the file has been safely closed.
1 |
csv_file.close() |
Now let’s see the complete code to write a new line in a CSV file using Python.
1 2 3 4 5 6 7 8 9 10 |
import csv csv_file = open('example.csv', 'w', newline='') csv_writer = csv.writer(csv_file) csv_writer.writerow(['Name', 'Age', 'City']) csv_writer.writerow(['Alice', '24', 'New York']) csv_writer.writerow(['Bob', '30', 'San Francisco']) csv_file.close() |
After running the above code, you’ll have a CSV file named example.csv
with the following content:
Name,Age,City Alice,24,New York Bob,30,San Francisco
Conclusion
In this tutorial, you’ve learned how to write a new line in a CSV file using Python. To recap, we’ve covered how to import the CSV module, create and open a CSV file for writing, create a CSV writer object, write rows to the file, and close the file. By following these steps, you can easily manipulate CSV data and create new CSV files with Python.