我试图打印文本文件n次,但出于某种原因,它只循环一次,这是我的代码。
def makeStrings():
k = int(raw_input("Enter the number of bits in each binary string: "))
n = int(raw_input("Enter the number of binary strings to create: "))
name = raw_input("Enter the name of the file: ")
fileName = name
outputFile = open(fileName, "w")
int(k)
int(n)
for i in range(0,n):
while(k>0):
randomNumber= int(random.randint(0,1))
outputFile.write(str(randomNumber))
k = k - 1
outputFile.write("\n")
outputFile.close()
如果你为k输入5,为n输入5,它应该写如下:
01110
11011
00011
11011
11100
到文件,但它只写1行 谁能给我一些见解?
答案 0 :(得分:3)
while(k>0):
您永远不会将k
重置为初始值。这个循环只发生一次
可能应该再次使用范围
for i in range(n):
for j in range(k):
# Don't subtract k...
或者,甚至将它全部缩小
with open(fileName, "w") as outputFile:
for i in range(n):
outputFile.write(''.join(str(random.randint(0,1)) for _ in range(k)))
outputFile.write("\n")