Hi

Am trying to get my head around using with in some code which is putting 2 files together using random.choice. How do I prevent repeats with random.choice?

with open(name, "r") as f1:
  beginnings = [word.rstrip(" \n") for word in f1]

with open("conjunct.txt", "r") as f2:
  endings = [word.rstrip(" \n") for word in f2]

with open(name, "w") as f3:
  for beginning in beginnings:
      f3.write('%s %s' % (beginning, random.choice(endings)))
      f3.write(os.linesep)

Thanks for any assist,
jkrueger

Use random.shuffle instead.

random.shuffle(endings)

for ctr, beginning in enumerate(beginnings):
    ## assumes there are at least as many endings as beginnings
    f3.write('%s %s\n' % (beginning, endings[ctr])

Edited 5 Years Ago by woooee: n/a

Thank you, I'm having a difficult time using with.
Everything after your code got an error, I have to do more with random etc., something I'm not getting.

with open(name, "w") as f3:
  random.shuffle(endings)

  for ctr, beginning in enumerate(beginnings):
    ## assumes there are at least as many endings as beginnings
    f3.write('%s %s\n' % (beginning, endings[ctr])
    f3.write(os.linesep)

Here is the error message.

f3.write(os.linesep)
     ^
SyntaxError: invalid syntax

Edited 5 Years Ago by jkrueger: need code example

Add one more closing parens to this line
f3.write('%s %s\n' % (beginning, endings[ctr]))

This question has already been answered. Start a new discussion instead.