Python program to read a random word from a file and write it into another file

Write a program to read random word from file and write it into another text file with Practical Example

Program Logic:

  • Import random module in program using import statement
  • Open input file say ‘name.txt’ in read mode using open method
  • Pass filename and access mode to open method of input file
  • Store path of input file in variable say ‘fin’
  • Open output file say ‘randomword.txt’ in write mode using open method
  • Pass filename and access mode to open method of output file
  • Store path of output file in variable say ‘fout’
  • Read whole content of input file using read function and store it in variable ‘str’
  • Use split function to convert line into word and store it in variable say ‘words’
  • Select random word from set of words using random.choice method
  • Display randomly selected word from input file using print method
  • Write random word into output file say ‘randomword.txt’
  • Close input file using close method
  • Close output file using close method

Below is implementation code/source code

import random 
fin = open("name.txt","r")
fout = open("randomword.txt","w+")
str = fin.read()
words = str.split()
data = random.choice(words)
print("Randomly selected word from name.txt file :",data)
fout.write(data)
fin.close()
fout.close()

Below is Output:

Randomly selected word from name.txt file : are

Below is Snapshot of Executable code with output

Below is input file “name.txt”

Below is Output file “randomword.txt

<