我有一串单词在 python shell 中以金字塔形式显示,但是当我尝试将它们移动到 .txt 文件时遇到问题。
问题是程序获取每个字符并将它们写入新文件,但它只写在第一行,只是用新的一行替换前一行,最后文件只包含最后一个行。
我尝试将 +'\n' 添加到写入函数,但结果是金字塔失去了对齐。
如果可以在文本文件中选择第一行、第二行等并写入它们,那将是解决方案,但我找不到这样的解决方案。
部分代码如下所示:
def pyramid(text):
for i in text:
line = string.center(i)
afile = open("name.txt", "w")
for row in text:
afile.write(row)
输入的“文本”是包含单词的嵌套列表。
请您参考如下方法:
问题是您在每次迭代时都以写入模式打开文件,因此每次文件都会先被截断,然后再写入新行。
在循环外打开文件。
In [18]: text=['words words','words words words','words words words words']
def pyramid(text):
with open("abc","w") as f:
max_width=len(text[-1])
for line in text:
f.write("{0:^{1}s}\n".format(line,max_width)) #use string formatting
....:
In [20]: pyramid(text)
In [21]: print open("abc").read()
words words
words words words
words words words words
^ : Forces the field to be centered within the available space.
