简体   繁体   English

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

[英]How to take a text file and create a copy but with numbered lines

This poem is saved in a text file: 这首诗保存在一个文本文件中:

'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

I want to create a copy of that file and change the name and have the output look like this: 我想创建该文件的副本并更改名称,并使输出看起来像这样:

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

Can this be done using a loop or is there a simpler way to do this? 可以使用循环来完成此操作吗?或者有更简单的方法来执行此操作吗?

You can iterate through each line of the poem file and get the line number using enumerate : 您可以遍历诗歌文件的每一行,并使用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))

The code above first opens the original poem file ( poem.txt ) and then opens a file for writing to it (hence the w as the second argument to open ). 上面的代码首先打开原始诗歌文件( poem.txt ),然后打开一个文件进行写入(因此, w作为第二个参数open )。 It then iterates through the lines of the original file and writes the line to the output file ( poem-numbered.txt ) with the line number. 然后,它遍历原始文件的各行,并将该行与行号一起写入输出文件( poem-numbered.txt )。

When passing w as the second argument to open , if the file already exists, it will be overwritten and if it doesn't exist, it will be created. 当将w作为第二个参数传递给open时 ,如果文件已经存在,它将被覆盖,如果文件不存在,则将创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM