Exporting variable to CSV file in Python
The CSV file or comma-separated values file is used to store and share data across platforms. The columns are separated by commas or other relevant delimiters, giving the data a tabular structure.
Sometimes we come across ready-made CSV files while sometimes we need to create one according to the requirements in our projects. Python can write CSV files using many modules. The csv module in Python’s standard library provides classes and methods to read & write data in CSV files.
To write in our CSV file, we use the following objects and methods of the csv module:
The writer() method
This function returns a writer object that converts data into a delimited string and stores it in a file object. The function needs a file object as a parameter. To prevent additional space between lines, the newline parameter is set to ‘’.
The writer class has the following methods:
- csv.writerow()– This function writes items in an iterable (list, tuple, or string), separating them by delimiter
- csv.writerows()– This function takes a list of iterables as a parameter, and writes each of them into new rows.
To write into a CSV file, let us start by creating a variable (List, Tuple, String). We would then export this variable into our file with the help of the above two csv module methods.
Examples 1: Exporting a list variable into csv file.
Example 2: Exporting a Tuple variable into csv file
Example 3: Exporting a string variable into CSV file
Similarly, we can write multiple rows into a CSV with the help of a 2-D list. This structure of data closely resembles a tabular Excel sheet with rows and columns.
The below code creates an input variable with a nested list of lists and tuples.
Note: Changes in the CSV file will be visible after the successful execution of the above code. You need to review your CSV file after each run.