1

I would like to write random prime numbers in new lines to a text file, but when I run my script it writes all numbers in one line. It's very likely that I don't understand something correctly.

This is my original code:

import random
file = open("prime.txt", "w")
i = 0
while( i<=100 ):
    temp=str(random.randint(1, 500) )
    file.writelines(temp)
    i += 1
file.close()

According to the answers, I just have to use the write() method with newline character (\n) instead of the writelines() method.

Bence László
  • 494
  • 2
  • 5
  • 14
  • 1
    Since you're only writing one string at atime, I think you just want `file.write(temp + "\n")` – CollinD Feb 24 '16 at 19:59
  • the answer that CollinD gave should work for you, for more info you can check [this](http://stackoverflow.com/questions/13730107/writelines-writes-lines-without-newline-just-fills-the-file) out – Jay T. Feb 24 '16 at 20:03

3 Answers3

3

writelines doesn't add line separators (which seems weird considering readlines removes them). You'll have to add them manually.

lines = ['{0}\n'.format(random.randint(1,500)) for i in range(100)]
file.writelines(lines)
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
3

You need to pass a sequence to writelines, you can use a generator expression and also use with to open your files replacing your while loop with a range:

import random
with  open("prime.txt", "w") as f:
   f.writelines(str(random.randint(1,500))+"\n" for _ in range(100))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

You can just add a newline when writing each number to the file. Also use file.write() instead of file.writelines(). Just use this as your code:

import random
file = open("primes.txt", "w")
i=0
while(i<=100):
    temp=str(random.randint(1,500))
    file.write(temp  + "\n")  #add a newline after each number
    i+=1
file.close()
Mark Skelton
  • 3,663
  • 4
  • 27
  • 47