0

Can someone check the code for me? I have three set of codes. The first part draws a random name from a file, name.txt and then displays it. The second code copies the drawn name into another file name2.txt and the third code is suppose to delete the drawn name from the first file. this is where I'm struggling to get it right. any help would be appreciated.

  import random

  #File path    
  g = r"C:\Users\Homer\name.txt"  
  lines = [line.rstrip('\n') for line in open(g)]

  #draw a random word  
  rand = random.choice(lines)

  # Display random word 
  print(rand) 

  # Append random word to name2.txt 
  with open("name2.txt",'a') as k:
        k.write(rand)
        k.write("\n")
        k.close()

  # Delete random word from orignal file (name.txt)
  g = with open("name.txt",'w')      
  lines = [line.rstrip('\n') for line in open(g)]        
  g.pop(rand)
Homer
  • 35
  • 10

1 Answers1

0

Use g without with, then use lines.remove and remove rand, then use writelines to write it back:

...

g = open("name.txt",'w')      
lines.remove(rand)
g.write('\n'.join(lines))
U13-Forward
  • 69,221
  • 14
  • 89
  • 114