如何获取文本文件并创建带有编号行的副本

2024-04-27 03:21:15 发布

您现在位置:Python中文网/ 问答频道 /正文

这首诗保存在一个文本文件中:

'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

这可以使用循环来完成吗?或者有更简单的方法来完成吗?你知道吗


Tags: andtheinallgyredidwerebrillig
1条回答
网友
1楼 · 发布于 2024-04-27 03:21:15

您可以遍历poem文件的每一行,并使用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文件(poem.txt),然后打开一个文件进行写入(因此w作为open的第二个参数)。然后它遍历原始文件的行,并用行号将行写入输出文件(poem-numbered.txt)。你知道吗

当将w作为第二个参数传递给open时,如果文件已经存在,它将被覆盖,如果它不存在,它将被创建。你知道吗

相关问题 更多 >