-1

I am attempting to write data to a .txt file. The data that is being written are the random integers from the randrange function in the following code.
I keep getting an error stating the object has no attribute when trying to write to the file.
Please help.

import random

def main():
    file_size = open('numbers.txt','w')

    file_size = random.randint(4, 7)

    print("file_size = ", file_size)

    for _ in range(file_size):
        random_num = random.randrange(5,20,2)
        if random_num % 2 ==1:
            print(random_num)

    file_size.write(str(random_num))

    file_size.close()
    print('Data has been written.')

main()
JDurstberger
  • 4,127
  • 8
  • 31
  • 68
CUSE
  • 3
  • 3
  • 2
    is you indentation correct ? and you are over writing the variable `file_size ` which is the root cause of the issue – The6thSense Nov 23 '15 at 06:21
  • Looking at your error it is clear that your indentation is not the fault. Your problem is you are overwriting `file_size ` to avoid this problem stop overwriting it. You might want to use context manager to open the file object – The6thSense Nov 23 '15 at 06:28

1 Answers1

0

You have big bug because file_size is first a stream then an int.
You have to use 2 different variables for file and file_size

Also I think you want to write every Number from the loop into the file therefore it has to go into your if-block:

import random   

def main():
    file = open('numbers.txt', 'w') #rename to file

    file_size = random.randint(4, 7)

    print("file_size = ", file_size)

    for _ in range(file_size):
        random_num = random.randrange(5, 20, 2)
        if random_num % 2 == 1:
            print(random_num)
            #use file not file_size
            file.write(str(random_num)+'\n') #write every odd number to stream?

    #use file not file_size    
    file.close()
    print('Data has been written.')


main()
JDurstberger
  • 4,127
  • 8
  • 31
  • 68