2013-07-25 3 views
0

나는 재미있는 프로그램을 만들고있다. 이것은 X 양의 파일을 Y의 랜덤 0과 1로 채우도록 입력해야합니다.중첩 루프 및 파일 io

이 파일을 실행할 때 각 파일에 20 개의 임의 0과 1로 채워진 2 개의 파일을 갖고 싶습니다. 내가 이것을 실행할 때 첫 번째 파일 만 채워지고 두 번째 파일은 비어있게됩니다.

제 두 번째 루프와 관련이 있다고 생각하지만 잘 모르겠습니다. 어떻게 작동합니까?

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

, 당신이 당신의 파일을 닫고 확인하십시오. 경우에 따라 버퍼가 디스크에 기록되기 전에 프로그램이 종료되면 출력이 파일에 기록되지 않습니다.

with statement을 사용하여 파일이 닫혔는지 확인할 수 있습니다. 파이썬의 실행 흐름이 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

당신은 0s1을 REINIT하지 않습니다. 따라서 두 번째로는 파일에 아무 것도 기록되지 않습니다. s1의 값을 다시 설정하라는 외에도

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 첫 번째 루프 이후에는 0으로 돌아 가지 않습니다. 그래서 다음 파일은 어떤 문자도 얻지 못합니다. 따라서 내부 루프 바로 앞에 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)))