XtheD
XtheD

Reputation: 57

How to print each of my output into a file

I am not quite sure how to print my output into a file.

Sample input

0
2
1
3
5

Content of dragon.dat for sample input

S
SLSLSRS
SLS
SLSLSRSLSLSRSRS
SLSLSRSLSLSRSRSLSLSLSRSRSLSRSRSLSLSLSRSLSLSRSRSRSLSLSRSRSLSRSRS

Here is my code:

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()

my ouput in the file:

SSLSLSRSSLSSLSLSRSLSLSRSRSSLSLSRSLSLSRSRSLSLSLSRSRSLSRSRSLSLSLSRSLSLSRSRSRSLSLSRSRSLSRSRS

How am I able to separate them into each lines just like the sample output?

Upvotes: 1

Views: 79

Answers (3)

erlc
erlc

Reputation: 680

Use print: print(B(1), file=infile) or

print(*[B(i) for i in [0,2,1,3,5]], file=infile, sep='\n')

Upvotes: 0

damned
damned

Reputation: 945

You are missing a \n while writing. Use infile.write(B(i) + '\n') instead.

Upvotes: 1

Owen
Owen

Reputation: 1736

infile.write("\n".join([B(i) for i in range(6)])

Upvotes: 0

Related Questions