0

Here's my code:

from random import random

f = open('Attractors1.txt', 'w')
for i in range(10):
    theta = (3.14/2)*random()
f.write(str(theta))

I'm trying to create a list of 10 theta values so I can call them in another program, but I don't think the objects are writing correctly. How do I know if I'm doing it write? Whenever I run the code and execute f.read() I get an error saying the file isn't open.

1
  • Thank you so much! This is my first time trying to write to file, and I'm having a hard time figuring out what I'm doing Commented Nov 4, 2013 at 21:43

2 Answers 2

3

You can't read from a file opened in write-only mode. :)

Since you're not writing within the loop, you'll only actually spit out a single number. Even if you fixed that, you'd get a bunch of numbers all in one line, because you're not adding newlines. .write isn't like print.

Also it's a good idea to use with when working with files, to ensure the file is closed when you think it should be.

So try this:

import math
from random import random

with open('Attractors1.txt', 'w') as f:
    for i in range(10):
        theta = (math.PI / 2) * random()
        f.write("{0}\n".format(theta))
Sign up to request clarification or add additional context in comments.

Comments

-1
f = open('Attractors1.txt', 'w')
for i in range(10):
  theta = (3.14/2)*random()
f.write(str(theta))
f.close()

Then to read:

f = open('Attractors1.txt','r')
text = f.read()
print text

Edit: wups beaten to it

1 Comment

this doesn't fix the write-outside-loop problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.