-1

I have this code:

import itertools
import string
variations = itertools.permutations(string.printable, 1)
for v in variations:
    text_file = open("Output.txt", "w")
    text_file.write(''.join(v))
    text_file.close()

But it doesn't work.When I run the .py file Output.txt is created but when I open it, I see an up arrow.I want to see an output like this:

1
2
3
4
...
  • Why are you opening and closing the file in each iteration? this will overwrite the file every time. just open and close once before/after the loop, or even better, use `with` – DeepSpace Dec 29 '19 at 11:43
  • @DeepSpace I'm not familiar with python. can you explain more, please? –  Dec 29 '19 at 11:44
  • See this https://stackoverflow.com/questions/19508703/how-to-open-a-file-through-python – DeepSpace Dec 29 '19 at 11:46
  • Passing `1` as the value for `r` to `itertools.permutations` will result in just returning a list with a tuple for each char in `string.printable`, this doesn't seem very useful? You may as well just loop over `string.printable` – Iain Shelvington Dec 29 '19 at 11:48
  • @Iain Shelvington It's just an example. I don't really want 1 as the value for r. –  Dec 29 '19 at 11:49

2 Answers2

0

You are opening and closing the file in every iteration with the w mode, which means the file gets truncated every iteration, which in turn means it will always contain only the last thing you wrote to it.

You may use the a mode which appends to the file.

A better approach will be to to open the file once before the loop, and close it once after the loop.

The best practice is to use the with context manager (google the term to find more info) which will handle the opening and closing of the file for you.

import itertools
import string

variations = itertools.permutations(string.printable, 1)

with open("Output.txt", "w") as f:
    for v in variations:
        f.write('{}\n'.format(''.join(v)))

Note that I added \n in the end of each line since I assumed you want each permutation in a separate line.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

Another way:

import itertools
import string
variations = itertools.permutations(string.printable, 1)

text_file = open("Output.txt", "w")
for v in variations:
    text_file.write(f"{v[0]}\n")

text_file.close()

As mentioned above there are better ways to do it. You are opening the file every iteration, only open it once. v is a tuple ('1',) etc. so you need to index the first element.

BpY
  • 403
  • 5
  • 12