Skip to content

Python write set to file

  • by

You can’t write a set to file in Python. It knows about lists and dictionaries, but not sets or tuples. But if you want to persist a pure python dataset you could use string conversion.

Python write set to file example

Simple example code Writing a set to an output file:

with open('set.txt', 'w') as f:
f.write(str({1, 3, (3, 5)}))

Output:

Python write set to file

To get a list from a set, call list() on it:

s = set(['item1', 'item2', 'item3'])
list(s)

Do comment if you have any doubts or suggestions on this Python file-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading