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.
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)
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.