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

我在文件中的输出:

SSLSLSRSSLSSLSLSRSLSLSRSRSSLSLSRSLSLSRSRSLSLSLSRSRSLSRSRSLSLSLSRSLSLSRSRSRSLSLSRSRSLSRSRS

我如何能够像示例输出一样将它们分成每一行?

4

3 回答 3

1

你错过了一段时间的\n写作。改为使用infile.write(B(i) + '\n')

于 2013-10-24T05:14:09.693 回答
0
infile.write("\n".join([B(i) for i in range(6)])
于 2013-10-24T05:09:54.637 回答
0

使用打印:print(B(1), file=infile)

print(*[B(i) for i in [0,2,1,3,5]], file=infile, sep='\n')
于 2013-10-24T05:17:34.883 回答