Last updated: Apr 9, 2024
Reading time·3 min
To write a list of tuples to a file:
with
statement to open the file.write()
method on the file object to write the list of tuples to
the file.with
statement takes care of automatically closing the file.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))
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.
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.
f
.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}
.
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.
1 bobby 2 hadz 3 com
str.format()
Alternatively, you can use the str.format()
method.
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 sample uses the str.format()
method instead of a formatted string
literal.
The str.format() method performs string formatting operations.
result = '{} {}'.format('hello', 'world') print(result) # 👉️ 'hello world'
The string the method is called on can contain replacement fields specified
using curly braces {}
.
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.
To write a list of tuples to a CSV file:
with
statement to open the CSV file.writerow()
method on the writer
object to write the list of
tuples to the file.with
statement takes care of automatically closing the file.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)
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.
1 bobby 2 hadz 3 com
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.
You can learn more about the related topics by checking out the following tutorials: