0

Okay so what I'm looking to do is output a set to a file in python. I have one file, it contains random strings. I first open the text file and read to check if any duplicates are seen, once finished I want to output the set back to the file.

Here's what I got

sets = set()

file1 = open("file1.txt", "r+")
for line in file1:
  sets.add(line)

file1.write(sets)

It says that write only takes the argument str and not set. Anyone know how to get around this?

Help would be appreciated.

poisonishere
  • 43
  • 1
  • 7
  • 3
    You must convert the set in a suitable string representation, maybe running a for-loop over the set or something simple like `"\n".join(sets)` – Michael Butscher Nov 04 '17 at 22:41
  • 2
    you should really listen to error strings you get, it literally tells you you need it as string, eg file1.write(str(sets)) (or use a proper serializer / deserializer if you want to read it later into a set) – Ronen Ness Nov 04 '17 at 22:42
  • @RonenNess Yeah mate I know it wants me to convert to a string, but I just wanted to know the most efficient way to do so. – poisonishere Nov 04 '17 at 22:48
  • @poisonishere depends on how you want the output to look. using str(sets) would give something like this 'set([1, 2, 3])', so you might want to use join like Michael proposed. I wouldn't worry about efficiency though, unless you're planning to process really huge files all the time it probably won't matter much. – Ronen Ness Nov 04 '17 at 22:52
  • I've just tried "\n".join(sets) and it's worked however it leaves a blank line between each string. Is there any way to keep them line after line? – poisonishere Nov 04 '17 at 22:58
  • You can save them with `pickle` (in Python 3 at least). See [**Saving an Object (Data persistence)**](https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence). – martineau Nov 04 '17 at 23:47

1 Answers1

0

Try this:

sets = set()

file1 = open("file1.txt", "r+")
for line in file1:
  sets.add(line)

file1.write(repr(sets))

Note the use of repr()—this will output a Python representation of the object to the file.

Lawrence D'Oliveiro
  • 2,768
  • 1
  • 15
  • 13