[英]Printing random data from list into file
我有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
(包括“/”)
嘗試:-
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行寫入新文件。
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.