How to Write Lists of Tuples to Files in Python
This guide explores several methods for writing a list of tuples to a file in Python. We'll cover techniques for plain text files using string formatting, as well as structured CSV files using the csv
module. You'll learn how to control the output format, add separators, and properly handle file I/O operations.
Writing Lists of Tuples to a Text File
To write a list of tuples to a plain text file, you can use a with open()
statement and a formatted string literal (f-string) or the str.format()
method.
Using f-strings
This approach utilizes f-strings for concise formatting and includes a newline character for readability.
list_of_tuples = [(1, 'tutorial'), (2, 'reference'), (3, 'com')]
with open('example.txt', 'w', encoding='utf-8') as f:
f.write('\n'.join(f'{tup[0]} {tup[1]}' for tup in list_of_tuples))
- The
with open()
statement opens a file in write mode (w
). - The
f'{tup[0]} {tup[1]}' for tup in list_of_tuples
expression creates the desired string representation of each tuple. - The
\n
.join joins the generated lines into a string, adding the newline\n
character between each tuple in the list, resulting in the file having each tuple on separate lines.
Using str.format()
You can also use the str.format()
method for string formatting, which also achieves the same result:
list_of_tuples = [(1, 'tutorial'), (2, 'reference'), (3, 'com')]
with open('example.txt', 'w', encoding='utf-8') as f:
f.write('\n'.join('{} {}'.format(*tup) for tup in list_of_tuples))
- The
*tup
unpacks the tuple values to the format method.
Writing Lists of Tuples to a CSV File
To write a list of tuples to a CSV file, you can use the csv
module, which helps to handle comma separated files.
import csv
list_of_tuples = [(1, 'tutorial'), (2, 'reference'), (3, 'com')]
with open('example.csv', 'w', encoding='utf-8') as f:
writer = csv.writer(f, delimiter=" ", skipinitialspace=True)
for tup in list_of_tuples:
writer.writerow(tup)
- We open the CSV file in writing mode (
w
). - The
csv.writer()
function creates a writer object that writes to a file according to the CSV specification. - The
writerow()
method writes the contents of each tuple into a row of the file. - The
delimiter
parameter is set to a space, to indicate that the tuple elements should be separated by a space, rather than a comma. - The
skipinitialspace
parameter will remove spaces that might be present before the delimiter, and between list items.
To use a comma as the delimiter, use the following instead:
import csv
list_of_tuples = [(1, 'tutorial'), (2, 'reference'), (3, 'com')]
with open('example.csv', 'w', encoding='utf-8') as f:
writer = csv.writer(f, delimiter=",", skipinitialspace=True)
for tup in list_of_tuples:
writer.writerow(tup)