Reputation: 113
I'm trying to generate a file containing a short list of random numbers. Every time I run this code I get a file where the list is truncated, usually in the middle of a number. I'm using PyCharm.
import random
def generate_test(l, r):
lst = []
for x in range(1,l):
lst = lst + [random.randrange(0, r)]
return lst
test = generate_test(100, 10**12)
test_file = open("test.txt", "wb")
test_file = open("test.txt", "r+")
test_file.write(str(test))
Upvotes: 0
Views: 571
Reputation: 977
Few things I'd like to mention, once you open a file you get that state of the file so if you write, you write in that state, but can't read newly written data. So you do not need to open a file in both(r,w) modes. And last thing I noticed, you didn't close the file.
import random
def generate_test(l, r):
lst = []
for x in range(1,l):
lst = lst + [random.randrange(0, r)]
return lst
test = generate_test(100, 10**12)
print(len(test)) # 99
test_file = open('test.txt', 'w')
test_file.write(str(test))
test_file.close()
Now read the file to verify the written data
test_file = open('test.txt','r')
data = test_file.read()
print(len(data.split())) # 99
test_file.close()
Upvotes: 1
Reputation: 1604
You don't create the file correctly, this might be a cleaner code:
import random
def generate_test(l, r):
lst = []
for x in range(1,l):
lst = lst + [random.randrange(0, r)]
return lst
test = generate_test(100, 10**12)
with open("test.txt", "w") as output:
output.write(str(test))
Upvotes: 1