试图在 txt 文件中写一个由星号组成的三角形,但在文件中没有以相同的格式打印
Trying to write a triangle made of asterisk in a txt file, but did not print in the same format in file
我的代码打印了一个由星号组成的直角三角形。我期望在文本文件中以相同的格式写入相同的三角形,但它并没有那样显示
rows = 1
cols = 1
thisfile = open(r'C:\AdarshNamdev\stars.txt', 'w')
while rows <= 10:
while cols <= (rows + 1):
star = " * " * cols
print(star)
thisfile.write(star)
cols += 1
rows += 1
thisfile.close()
需要进行哪些更改才能获得所需的输出?
默认情况下,.write
不写换行符。您需要添加它,如下所示:
thisfile.write(star + '\n')
我的代码打印了一个由星号组成的直角三角形。我期望在文本文件中以相同的格式写入相同的三角形,但它并没有那样显示
rows = 1
cols = 1
thisfile = open(r'C:\AdarshNamdev\stars.txt', 'w')
while rows <= 10:
while cols <= (rows + 1):
star = " * " * cols
print(star)
thisfile.write(star)
cols += 1
rows += 1
thisfile.close()
需要进行哪些更改才能获得所需的输出?
默认情况下,.write
不写换行符。您需要添加它,如下所示:
thisfile.write(star + '\n')