如何在python中将随机数写入文件

时间:2016-08-08 09:01:15

标签: python list file

我想在文件中存储100个随机抽取的数字。 如何使用文件将随机数写入列表? 我怎样才能读取文件? 如何分隔抽奖号码

import random
draw = [] 

while True:
    numbers_lotto = random.randint(1,50)    
    draw.append(numbers_lotto)
    if len(draw) == 5 # the numbers?
        break

1 个答案:

答案 0 :(得分:1)

import random

file_name = 'random_numbers.txt'

with open ('file_name', 'w') as a_file:
    for i in range (100):
        a_file.write ('{}\n'.format (random.random ()))

with open ('file_name', 'r') as a_file:
    a_list = [float (word) for word in a_file.read () .split ()]

print (a_list)

import random
import pickle

file_name = 'random_numbers.txt'

with open (file_name, 'wb') as a_file:
    pickle.dump ([random.random () for i in range (100)], a_file)

with open (file_name, 'rb') as a_file:
    a_list = pickle.load (a_file)

print (a_list)