Write a List of Tuples to a File in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
3 min

banner

# Table of Contents

  1. Write a List of Tuples to a File in Python
  2. Write a List of Tuples to a File using str.format()
  3. Write a List of Tuples to a CSV file in Python

# 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
list_of_tuples = [(1, 'bobby'), (2, 'hadz'), (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 code for this article is available on GitHub
The with open() syntax takes care of automatically closing the file even if an exception is raised.

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

main.py
list_of_tuples = [(1, 'bobby'), (2, 'hadz'), (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))

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 bobby 2 hadz 3 com

# Write a List of Tuples to a File using str.format()

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

main.py
list_of_tuples = [(1, 'bobby'), (2, 'hadz'), (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 code for this article is available on GitHub

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, 'bobby'), (2, 'hadz'), (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)
The code for this article is available on GitHub

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 bobby 2 hadz 3 com
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.