2013-07-25 25 views
0

我正在製作一個簡單的程序爲樂趣。這應該爲X數量的文件填充Y量的隨機0和1。嵌套循環和文件io

當我運行這個我想有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

除了正在重置的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))) 
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 
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)))