How To Write New Line In CSV File Python

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:

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.

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.

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.

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.

Now let’s see the complete code to write a new line in a CSV file using Python.

After running the above code, you’ll have a CSV file named example.csv with the following content:

Alice,24,New York
Bob,30,San Francisco


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.