Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting a randomly generated list into a seperate .txt file without repeating

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading