嵌套循环和文件io

时间:2013-07-25 22:10:21

标签: python loops file-io

我正在制作一个简单的程序以获得乐趣。这应该输入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)))

3 个答案:

答案 0 :(得分:3)

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

您可以使用with statement保证文件已关闭。 当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)))

答案 1 :(得分:0)

您不会将s1重新发送到0。所以第二次没有任何内容写入文件。

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

答案 2 :(得分: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)))