将列表中的随机数据打印到文件中

时间:2019-05-28 02:56:50

标签: python python-3.x

我有3个列表

x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]

我需要每次将x,y和z随机写入一个文件到新行中。

Keyword = input("Directory to list")

with open(Keyword) as f: 
        content = f.readlines()

    content = [x.strip() for x in content]

    with open("test.txt") as w:
        w.write(PageFormat + )

输出应如下所示:

2 // 6 // 8

3 // 4 // 9

1 // 5 // 9

2 // 5 // 9

1 // 4 // 7

(包括“ /”)

2 个答案:

答案 0 :(得分:0)

尝试:-

import random


x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]


file = open("new.txt",'w')

for a in range(0, 10):
    file.write(x[random.randrange(0,3)] + " // " + y[random.randrange(0,3)] + " // " + z[random.randrange(0,3)] + "\n")

file.close()

样品输出:-

2 // 4 // 9
1 // 6 // 9
2 // 5 // 9
1 // 6 // 8
1 // 5 // 8
3 // 5 // 9
3 // 4 // 7
2 // 6 // 7
1 // 5 // 7
2 // 4 // 8

您可以通过更改range()的第二个参数来控制迭代次数。该程序将10行写入一个新文件。

答案 1 :(得分:0)

from random import choice

x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]

with open("test.txt", "w") as fp:
    fp.write(choice(x) + "//" + choice(y) + "//" + choice(z))