user2954167
user2954167

Reputation: 154

How do I write a list of strings to a file in Python?

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.

Upvotes: 0

Views: 140

Answers (2)

David Yang
David Yang

Reputation: 2141

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

Upvotes: -1

Eevee
Eevee

Reputation: 48546

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))

Upvotes: 3

Related Questions