- How to Convert Tuples to a CSV File in Python [4 Ways]
- Method 1: Python’s CSV Module
- Method 2: Pandas DataFrame to_csv()
- Method 3: NumPy savetext()
- Method 4: Pure Python Without External Dependencies
- Related Video
- How to Create a CSV File in Python?
- How to Create CSV File in Python?
- CSV Module Functions in Python
- How to Open a CSV File in Python?
- How to Close a CSV File in Python?
- Methods to Create CSV File in Python
- Method 1: Using csv.writer Class
- Method 2: Using csv.DictWriter Class
- Extra Examples of Working with CSV File in Python
- Conclusion
- Read More:
How to Convert Tuples to a CSV File in Python [4 Ways]
Problem: How to convert one or more tuples to a csv file?
Example: Given is a tuple or list of tuples—for example, salary data of employees in a given company:
salary = [('Alice', 'Data Scientist', 122000), ('Bob', 'Engineer', 77000), ('Ann', 'Manager', 119000)]
Your goal is to write the content of the list of tuples into a comma-separated-values (CSV) file format. Your out file should look like this:
# file.csv Alice,Data Scientist,122000 Bob,Engineer,77000 Ann,Manager,119000
Note that writing a single tuple to a CSV is a subproblem of writing multiple tuples to a CSV that can be easily solved by passing a list with a single tuple as an input to any function we’ll discuss in the article.
Solution: There are four simple ways to convert a list of tuples to a CSV file in Python.
- CSV: Import the csv module in Python, create a csv writer object, and write the list of tuples to the file in using the writerows() method on the writer object.
- Pandas: Import the pandas library, create a Pandas DataFrame, and write the DataFrame to a file using the DataFrame method DataFrame.to_csv(‘file.csv’) .
- NumPy: Import the NumPy library, create a NumPy array, and write the output to a CSV file using the numpy.savetxt(‘file.csv’, array, delimiter=’,’) method.
- Python: Use a pure Python implementation that doesn’t require any library by using the Python file I/O functionality.
My preference is method 2 (Pandas) because it’s simplest to use and most robust for different input types (numerical or textual).
🧩 Try It Yourself: Before we dive into these methods in more detail, feel free to play with them in our interactive code shell. Simply click the “Run” button and find the generated CSV files in the “Files” tab.
Do you want to develop the skills of a well-rounded Python professional—while getting paid in the process? Become a Python freelancer and order your book Leaving the Rat Race with Python on Amazon (Kindle/Print)!
Method 1: Python’s CSV Module
You can convert a list of tuples to a CSV file in Python easily—by using the csv library. This is the most customizable of all four methods.
salary = [('Alice', 'Data Scientist', 122000), ('Bob', 'Engineer', 77000), ('Ann', 'Manager', 119000)] # Method 1 import csv with open('file.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerows(salary)
# file.csv Alice,Data Scientist,122000 Bob,Engineer,77000 Ann,Manager,119000
In the code, you first open the file using Python’s standard open() command. Now, you can write content to the file object f .
Next, you pass this file object to the constructor of the CSV writer that implements some additional helper method—and effectively wraps the file object providing you with new CSV-specific functionality such as the writerows() method.
You now pass a list of tuples to the writerows() method of the CSV writer that takes care of converting the list of tuples to a CSV format.
You can customize the CSV writer in its constructor (e.g., by modifying the delimiter from a comma ‘,’ to a whitespace ‘ ‘ character). Have a look at the specification to learn about advanced modifications.
Method 2: Pandas DataFrame to_csv()
You can convert a tuple or list of tuples to a Pandas DataFrame that provides you with powerful capabilities such as the to_csv() method. This is the easiest method and it allows you to avoid importing yet another library (I use Pandas in many Python projects anyways).
salary = [('Alice', 'Data Scientist', 122000), ('Bob', 'Engineer', 77000), ('Ann', 'Manager', 119000)] # Method 2 import pandas as pd df = pd.DataFrame(salary) df.to_csv('file2.csv', index=False, header=False)
# file2.csv Alice,Data Scientist,122000 Bob,Engineer,77000 Ann,Manager,119000
You create a Pandas DataFrame—which is Python’s default representation of tabular data. Think of it as an Excel spreadsheet within your code (with rows and columns).
The DataFrame is a very powerful data structure that allows you to perform various methods. One of those is the to_csv() method that allows you to write its contents into a CSV file.
You set the index and header arguments of the to_csv() method to False because Pandas, per default, adds integer row and column indices 0, 1, 2, ….
Again, think of them as the row and column indices in your Excel spreadsheet. You don’t want them to appear in the CSV file so you set the arguments to False .
If you want to customize the CSV output, you’ve got a lot of special arguments to play with. Check out this article for a comprehensive list of all arguments.
Method 3: NumPy savetext()
NumPy is at the core of Python’s data science and machine learning functionality. Even Pandas uses NumPy arrays to implement critical functionality.
You can convert a list of tuples to a CSV file by using NumPy’s savetext() function and passing the NumPy array as an argument that arises from the conversion of the list of tuples.
This method is best if you have numerical data only—otherwise, it’ll lead to complicated data type conversions which are not recommended.
a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] # Method 3 import numpy as np a = np.array(a) np.savetxt('file3.csv', a, delimiter=',')
# file3.csv 1.000000000000000000e+00,2.000000000000000000e+00,3.000000000000000000e+00 4.000000000000000000e+00,5.000000000000000000e+00,6.000000000000000000e+00 7.000000000000000000e+00,8.000000000000000000e+00,9.000000000000000000e+00
The output doesn’t look pretty: it stores the values as floats. But no worries, you can reformat the output using the format argument fmt of the savetxt() method (more here). However, I’d recommend you stick to method 2 (Pandas) to avoid unnecessary complexity in your code.
Method 4: Pure Python Without External Dependencies
If you don’t want to import any library and still convert a list of tuples into a CSV file, you can use standard Python implementation as well: it’s not complicated and efficient. However, if possible you should rely on libraries that do the job for you.
This method is best if you won’t or cannot use external dependencies.
salary = [('Alice', 'Data Scientist', 122000), ('Bob', 'Engineer', 77000), ('Ann', 'Manager', 119000)] # Method 4 with open('file4.csv','w') as f: for row in salary: for x in row: f.write(str(x) + ',') f.write('\n')
# file4.csv Alice,Data Scientist,122000, Bob,Engineer,77000, Ann,Manager,119000,
In the code, you first open the file object f . Then you iterate over each row and each element in the row and write the element to the file—one by one. After each element, you place the comma to generate the CSV file format. After each row, you place the newline character ‘\n’ .
Note: to get rid of the trailing comma, you can check if the element x is the last element in the row within the loop body and skip writing the comma if it is.
Related Video
The following video shows how to convert a list of lists to a CSV in Python, converting a tuple or list of tuples will be similar:
How to Create a CSV File in Python?
CSV stands for comma-separated values , which is a simple file format to store data in a structured layout. A CSV file stores and arranges tabular data such as a spreadsheet or database in the form of plain text. Each row in a CSV file is referred to as a data record. Each data record has one or more fields (columns) separated by commas. Therefore, the comma acts as a delimiter (character that identifies the beginning or the end of a data value) here.
How to Create CSV File in Python?
To create a CSV file and write data into it using Python, we have to follow a certain set of instructions:
- Open the CSV file in writing ( w mode) with the help of open() function
- Create a CSV writer object by calling the writer() function of the csv module
- Write data to CSV file by calling either the writerow() or writerows() method of the CSV writer object
- Finally, close the CSV file
CSV Module Functions in Python
CSV module is used to read/ write CSV files in Python. To use the csv module in our program we have to first import using the following statement:
Before learning about different types of functions let us study in brief about dialects, Dialects are used to group multiple formatting patterns like delimiter, skipinitialspace, quoting, and escapechar into a single dialect name, thus removing redundancy when working with multiple files. We will learn more about dialects later in this article.
Different types of functions in the csv module are as follows:
- csv.field_size_limit — This function returns the current maximum field size allowed by the parser.
- csv.get_dialect — It returns the dialect associated with a name.
- csv.list_dialects — It returns the names of all registered dialects.
- csv.reader — This function reads the data from a CSV file.
- csv.register_dialect — It associates dialect with a name, and the name must be a string or a Unicode object.
- csv.writer — This function writes the data to a CSV file.
- csv.unregister_dialect — It deletes the dialect, which is associated with the name from the dialect registry. If a name is not a registered dialect name, then an error is raised.
- csv.QUOTE_ALL — It instructs the writer objects to quoting all fields.
- csv.QUOTE_MINIMAL — It instructs the writer to quote only those fields containing special characters such as quote char, delimiter, etc.
- csv.QUOTE_NONNUMERIC — It instructs the writer objects to quote all the non-numeric fields.
- csv.QUOTE_NONE — It instructs the writer object never to quote the fields.
How to Open a CSV File in Python?
There are two common methods of opening a CSV file, one is using the csv module and other is using the pandas library.
How to Close a CSV File in Python?
If we are working with the file using the with keyword, it allows us to both open and close the file without having to explicitly close it.
In case we have opened the file using the open(filename.csv) method, we have to explicitly close it using the .close() method. The .close() method is used to close the opened file. Once a file is closed, we cannot perform any operations on it.
Methods to Create CSV File in Python
Python’s in-built csv module helps us to deal with CSV files. There are various classes provided by this module for writing to CSV:
Method 1: Using csv.writer Class
The csv.writer class is used to insert data in CSV files. It returns a writer object which is responsible for converting the user’s data into a delimited string. A CSV file object should be opened with newline=» otherwise newline characters inside the quoted fields will not be interpreted correctly
Syntax for csv.writer Class
- csvfile — file object having write() method
- dialect — It is an optional parameter that specifies the name of the dialect to be used
- fmtparams — Certain optional formatting parameters that are used to overwrite the parameters specified in the dialect
csv.writer class provides two methods for writing data in a CSV file, which include the following
- writerow() : This method is used when we want to write only a single row at a time in our CSV file. writerow() can be used to write field rows. Syntax
Method 2: Using csv.DictWriter Class
The objects created using the csv.DictWriter() class are used to write to a CSV file from a Python dictionary.
Syntax for «csv.DictWriter» class
- csvfile — file object having write() method
- fieldnames — this parameter includes a sequence of keys that identify the order in which values in the dictionary should be passed
- restval(optional) — This parameter specifies the value to be written if the dictionary is missing a key in fieldnames
- extrasaction(optional) — this parameter is used to indicate what action to take if a key is not found in fieldnames, if it is set to raise a ValueError will be raised
- dialect(optional) — it is the name of the dialect to be used
csv.DictWriter class provides two methods for writing data in a CSV file, which include the following
- writeheader() : This method is used to simply write the first row in our CSV file using pre-defined field names. Syntax
Extra Examples of Working with CSV File in Python
- Creating CSV file with custom delimiters A CSV file uses comma , as the default delimiter, but we can also use custom delimiters such as | or \t etc. In the example below we will see the implementation of how to create a CSV file having pipe | delimiter:
Conclusion
- CSV stands for comma-separated values, which is a simple file format to store data in a structured format.
- Python’s in-built CSV module helps us to deal with CSV files. There are various classes provided by this module for writing to CSV:
- Using csv.writer class
- Using csv.DictWriter class
Read More: