Write a list of tuples to a File in Python

avatar

Borislav Hadzhiev

Last updated: Aug 30, 2022

banner

Photo from Unsplash

Write a list of tuples to a File in Python #

To write a list of tuples to a file:

  1. Use the with statement to open the file.
  2. Use the write() method on the file object to write the list of tuples to the file.
  3. The with statement takes care of automatically closing the file.
main.py
import csv list_of_tuples = [(1, 'one'), (2, 'two'), (3, 'three')] # ✅ Write list of tuples to text file (formatted string literal) 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)) # -------------------------------------------- # ✅ Write list of tuples to text file (str.format()) with open('example.txt', 'w', encoding='utf-8') as f: f.write('\n'.join('{} {}'.format(*tup) for tup in list_of_tuples)) # -------------------------------------------- # ✅ Write list of tuples to CSV file 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)
The with open() syntax takes care of automatically closing the file even if an exception is raised.

The first example uses a formatted string literal to format the tuple's contents.

main.py
list_of_tuples = [(1, 'one'), (2, 'two'), (3, 'three')] 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))

We opened a file called example.txt in write mode.

We used a formatted string literal to access the values in each tuple.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

Make sure to wrap expressions in curly braces - {expression}.

The tuples in the list contain 2 elements. If your tuples contain more elements, make sure to include them in the f-string.

We used the str.join() method to join the strings with a newline (\n) separator.

After running the script, the example.txt file contains the contents of each tuple on a separate line.

example.txt
1 one 2 two 3 three

Alternatively, you can use the str.format() method.

main.py
list_of_tuples = [(1, 'one'), (2, 'two'), (3, 'three')] with open('example.txt', 'w', encoding='utf-8') as f: f.write('\n'.join('{} {}'.format(*tup) for tup in list_of_tuples))

The code sample uses the str.format() method instead of a formatted string literal.

The str.format method performs string formatting operations.

main.py
result = '{} {}'.format('hello', 'world') print(result) # 👉️ 'hello world'

The string the method is called on can contain replacement fields specified using curly braces {}.

Make sure to provide exactly as many arguments to the format() method as you have replacement fields in the string.

For example, if the tuples in your list contain 3 elements, make sure to specify 3 replacement fields.

Write a list of tuples to a CSV file in Python #

To write a list of tuples to a CSV file:

  1. Use the with statement to open the CSV file.
  2. Use the writerow() method on the writer object to write the list of tuples to the file.
  3. The with statement takes care of automatically closing the file.
main.py
import csv list_of_tuples = [(1, 'one'), (2, 'two'), (3, 'three')] 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 opened a file called example.csv in write mode.

The csv.writer method returns a writer object that is used to convert data into delimited strings.

We used a space for the delimiter argument, so the elements of each tuple are separated by spaces.

example.csv
1 one 2 two 3 three
You can set the delimiter keyword argument to a comma if you need to separate the tuple's elements with a comma.

When the skipinitialspace argument is set to True, whitespace that immediately follows the delimiter is ignored.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.