2013-10-24 5 views
1

Я не совсем уверен, как печатать выходные данные в файле.Как распечатать каждый мой вывод в файл

ввода образца

0 
2 
1 
3 
5 

Содержание dragon.dat для ввода образца

S 
SLSLSRS 
SLS 
SLSLSRSLSLSRSRS 
SLSLSRSLSLSRSRSLSLSLSRSRSLSRSRSLSLSLSRSLSLSRSRSRSLSLSRSRSLSRSRS 

Вот мой код:

infile = open("dragon.dat", "w") 
def B(n): 
    if n>22: 
     return "Enter integer less than 22" 

    elif n==0: 
     return "S" 
    str=B(n-1) 
    reversestr=str 
    str +="L" 
    reversestr=reversestr.replace("L","T") 
    reversestr=reversestr.replace("R","L").replace("T","R") 
    reversestr=reversestr[::-1] 
    return str + reversestr 

print(B(0)) # these input will be printed in the python shell 
print(B(2)) 
print(B(1)) 
print(B(3)) 
print(B(5)) 

infile.write(B(0)) 
infile.write(B(2)) 
infile.write(B(1)) 
infile.write(B(3)) 
infile.write(B(5)) 


infile.close() 

мой Ouput в файле:

SSLSLSRSSLSSLSLSRSLSLSRSRSSLSLSRSLSLSRSRSLSLSLSRSRSLSRSRSLSLSLSRSLSLSRSRSRSLSLSRSRSLSRSRS 

Как я могу отделить их в каждой строке так же, как и выходной образец?

+2

Используйте ' '\ n'':' infile.write (В (0) + '\ N') ' –

ответ

1

Вам не хватает \n во время записи. Вместо этого используйте infile.write(B(i) + '\n').

0

Использование печати: print(B(1), file=infile) или

print(*[B(i) for i in [0,2,1,3,5]], file=infile, sep='\n') 
Смежные вопросы