mardi 26 février 2019

Deleting a name from a text file in Python

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)




Aucun commentaire:

Enregistrer un commentaire