这首诗保存在一个文本文件中:
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogroves,
And the mom raths outgrabe.
- Lewis Carroll
我想创建该文件的副本并更改名称并使输出如下所示:
1: 'Twas brillig, and the slithy toves 2: Did gyre and gimble in the wabe; 3: All mimsy were the borogroves, 4: And the mom raths outgrabe. 5: - Lewis Carroll
这可以使用循环来完成还是有更简单的方法来做到这一点?
请您参考如下方法:
您可以遍历诗歌文件的每一行并使用 enumerate 获取行号:
with open('poem.txt') as poem_file:
with open('poem-numbered.txt', 'w') as numbered_file:
for index, line in enumerate(poem_file, 1):
numbered_file.write('{}: {}'.format(index, line))
上面的代码首先打开原始诗歌文件 ( poem.txt ),然后打开一个文件写入它(因此 w 作为 open 的第二个参数)。然后它遍历原始文件的行,并将该行与行号一起写入输出文件 ( poem-numbered.txt )。
通过时w作为 open 的第二个参数, 如果文件已经存在,则覆盖,如果不存在,则创建。
