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](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2023/02/Python-write-set-to-file.jpg?resize=700%2C325&ssl=1)
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.