#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    5
    Rep Power
    0

    File writing help


    newbie here, trying to finish up my express course of intro to programming, my first of three assignments this week is:

    A program named filemake.py that generates 10 random integers, all in the range from 1-10, and writes each integer on its own line to a file named mynumbers.txt. This program must use a loop.

    this is the code i have thus far but the problem i'm running into is its generating the same number for all 10 lines....need it to generate a random one each line....
    -----------------------------------
    import random


    def main():
    numbers = random.randint(1, 10)

    output_file = open('mynumbers.txt','w')

    for i in range(10):
    output_file.write(str(numbers) + '\n')

    output_file.close()
    print ('File successfully created')

    main()
    ------------------------------------

    thanks in advance. sorry if this may be simple, first introduction to programming.....
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    5
    Rep Power
    0
    ok so i solved the first issue, i now have a working program that reads the numbers and adds them and gives the total....but i need to use a loop, need assistance on what to use for the loop instead of what i have below:

    def main():
    infile = open('mynumbers.txt', 'r')

    num1 = int(infile.readline())
    num2 = int(infile.readline())
    num3 = int(infile.readline())
    num4 = int(infile.readline())
    num5 = int(infile.readline())
    num6 = int(infile.readline())
    num7 = int(infile.readline())
    num8 = int(infile.readline())
    num9 = int(infile.readline())
    num10 = int(infile.readline())


    infile.close()

    total = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10

    print ('The total of the random numbers is:', total)

    main()
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2014
    Posts
    5
    Rep Power
    0
    have this so far but need it to add the numbers now....



    def main():
    infile = open('mynumbers.txt', 'r')

    line = infile.readline()

    print ('The random numbers were:')
    while line:
    print (line)
    line = infile.readline()



    infile.close()

    total = (line)

    print ('The total of the random numbers is:', total)

    main()

IMN logo majestic logo threadwatch logo seochat tools logo