![]() |
|
[Tut] How to Convert Tuples to a CSV File in Python [4 Ways] - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Convert Tuples to a CSV File in Python [4 Ways] (/thread-99323.html) |
[Tut] How to Convert Tuples to a CSV File in Python [4 Ways] - xSicKxBot - 05-02-2022 How to Convert Tuples to a CSV File in Python [4 Ways] Problem: How to convert one or more tuples to a Code: csvExample: Given is a tuple or list of tuples—for example, salary data of employees in a given company: Code: 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: Code: # file.csv
Alice,Data Scientist,122000
Bob,Engineer,77000
Ann,Manager,119000Note 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.
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 methodsin 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. Try It Yourself: Click to run in interactive shell!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 Code: csvCode: 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)Output: Code: # file.csv
Alice,Data Scientist,122000
Bob,Engineer,77000
Ann,Manager,119000In the code, you first open the file using Python’s standard Code: open()Code: fNext, 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 Code: writerows()You now pass a list of tuples to the Code: writerows()You can customize the CSV writer in its constructor (e.g., by modifying the delimiter from a comma Code: ','Code: ' 'Method 2: Pandas DataFrame to_csv() ![]() You can convert a tuple or list of tuples to aPandas DataFrame that provides you with powerful capabilities such as the Code: to_csv()Code: 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)Output: Code: # file2.csv
Alice,Data Scientist,122000
Bob,Engineer,77000
Ann,Manager,119000You 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 Code: to_csv()You set the Code: indexCode: headerCode: to_csv()Code: FalseAgain, 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 Code: FalseIf you want to customize the CSV output, you’ve got a lot of special arguments to play with. Check out thisarticle for a comprehensive list of all arguments. ![]() Related article:Pandas Cheat Sheets to Pin to Your Wall Method 3: NumPy savetext() NumPyis 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 Code: savetext()This method is best if you have numerical data only—otherwise, it’ll lead to complicated data type conversions which are not recommended. Code: 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=',')Output: Code: # 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+00The output doesn’t look pretty: it stores the values as floats. But no worries, you can reformat the output using the format argument Code: fmtCode: savetxt()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. Code: 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')Output: Code: # file4.csv
Alice,Data Scientist,122000,
Bob,Engineer,77000,
Ann,Manager,119000,In the code, you first open the file object Code: fCode: '\n'Note: to get rid of the trailing comma, you can check if the element Code: xRelated: Join the Finxter community and download your 8+ Python cheat sheets to refresh your code understanding. 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: Where to Go From Here? Enough theory. Let’s get some practice! Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs? You build high-value coding skills by working on practical coding projects! Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people? If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! |