0

我正在制作一个简单的程序来娱乐。这应该输入 X 数量的文件以填充 Y 数量的随机 0 和 1。

当我运行它时,我希望有 2 个文件在每个文件中都填充 20 个随机 0 和 1。在我运行它的那一刻,只有第一个文件被填满,第二个文件是空的。

我认为这与我的第二个循环有关,但我不确定,我怎样才能让它工作?

import random

fileamount = int(raw_input("How many files should I make? > "))
amount = int(raw_input("How many characters in the files? > "))
print "I will now make %r files with %r characters in them!\n" % (fileamount, amount)
s1 = 0
s2 = 0

while s2 < fileamount:
    s2 = s2 + 1
    textfile = file('a'+str(s2), 'wt')
    while s1 < amount:
        s1 = s1 + 1
        textfile.write(str(random.randint(0,1)))
4

3 回答 3

3

除了重置 的值外s1,请确保关闭文件。有时,如果程序在缓冲区写入磁盘之前结束,则输出不会写入文件。

您可以使用with语句来保证文件已关闭。当 Python 的执行流程离开with套件时,该文件将被关闭。

import random

fileamount = int(raw_input("How many files should I make? > "))
amount = int(raw_input("How many characters in the files? > "))
print "I will now make %r files with %r characters in them!\n" % (fileamount, amount)

for s2 in range(fileamount):
    with open('a'+str(s2), 'wt') as textfile:
        for s1 in range(amount):
            textfile.write(str(random.randint(0,1)))
于 2013-07-25T22:14:51.437 回答
0

你没有重新初始化s10. 所以第二次不会有任何东西写入文件。

import random

fileamount = int(raw_input("How many files should I make? > "))
amount = int(raw_input("How many characters in the files? > "))
print "I will now make %r files with %r characters in them!\n" % (fileamount, amount)

s2 = 0
while s2 < fileamount:
    s2 = s2 + 1
    textfile = open('a'+str(s2), 'wt') #use open
    s1 = 0
    while s1 < amount:
        s1 = s1 + 1
        textfile.write(str(random.randint(0,1)))
    textfile.close() #don't forget to close
于 2013-07-25T22:12:46.177 回答
0

s2第一次循环后不会回到零。所以下一个文件没有任何字符。所以放在s2=0内部循环之前。

更好地使用range功能。

import random

fileamount = int(raw_input("How many files should I make? > "))
amount = int(raw_input("How many characters in the files? > "))
print "I will now make %r files with %r characters in them!\n" % (fileamount, amount)

for s2 in range(fileamount):
    textfile = file('a'+str(s2+1), 'wt')
    for b in range(amount):
        textfile.write(str(random.randint(0,1)))
于 2013-07-25T22:20:26.697 回答