'I have a text file which contains sets , how do i read them as sets when i load on python? [closed]

My text file looks like this

{} /n {}/n

When I use readline, I get it as a list , like ['{}' , '{}]

how do I remove the string and read them as sets?



Solution 1:[1]

This code work for you.

with open('yourfile.txt','r') as file:
    data = file.read().splitlines()
    data = [set(a[1:-1].split(',')) for a in data]
print(data)

You can use eval also here, But using eval might be dangerous.

with open('yourfile.txt','r') as file:
    data = file.read().splitlines()
    data = [eval(a) for a in data]
print(data)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1