有没有人知道如何为函数保存多个打印的字符串?我能够绘制金字塔,但我仍然坚持将其写入文件。
这是我的代码:
n = int(input("Enter number: "))
file_1 = open("pyramid.txt", "a")
for i in range(1, n + 1):
for j in range(1, n - i + 1):
file_1.write(" ", end="")
for j in range(1, i + 1):
file_1.write("* ", end="")
print("")
file_1.close()
答案 0 :(得分:1)
你的代码有点坏了。您正在打印以创建换行符,但将其余部分写入文件。
将金字塔输出到stdout(终端输出):
n = int(input("Enter number: "))
for i in range(1, n + 1):
for j in range(1, n - i + 1):
print(" ", end="")
for j in range(1, i + 1):
print("* ", end="")
print("")
将其输出到文件:
n = int(input("Enter number: "))
file_1 = open("pyramid.txt", "a")
for i in range(1, n + 1):
for j in range(1, n - i + 1):
file_1.write(" ")
for j in range(1, i + 1):
file_1.write("* ")
file_1.write("\n")
file_1.close()
缩短:
n = int(input("Enter number: "))
print("\n".join(" " * (n - i) + "* " * i for i in range(1, n + 1)))
或
n = int(input("Enter number: "))
f = open("pyramid.txt", "w")
f.write("\n".join(" " * (n - i) + "* " * i for i in range(1, n + 1)) + "\n")
f.close()