Home > front end >  Getting a randomly generated list into a seperate .txt file without repeating
Getting a randomly generated list into a seperate .txt file without repeating

Time:12-08

import random
list=[]
while True:
  try:
    n= int(input("Enter number of variables:"))
    if n > 0:
       for j in range(n):
           list.append(random.randint(1, 20))
       print('Randomised list is: ', list)
       break;
    else:
      print("The variable entered should be higher than 0")
  except:
    continue

def addMax(nums):
    m = max(nums)
    for list in range(len(nums)):
        nums[list]  = m
    return nums
print('The new list reads: ',addMax(list))

def ListtoString(list):
    str(list)
with open('output.txt', 'w') as f:
    for nums in list:
        f.writelines('%s\n' % list)
    f.close()

I am currently trying to take a randomly generated list and put it into a separate .txt file. I have been able to get the list into a separate file but the problem I have is that it repeats 5 times(or a different number depending what I put into the initial input of "Enter number of variables". I am looking for it to just write the randomly generated list one time and have struggled to do so. Any suggestions or tips?

CodePudding user response:

with open('output.txt', 'w') as f:
   f.write('\n'.join(map(str, list)))
  • Related