python - How to take a text file and create a copy but with numbered lines -


this poem saved in text file:

 'twas brillig, , slithy toves    did gyre , gimble in wabe; mimsy borogroves,    , mom raths outgrabe.                - lewis carroll 

i want create copy of file , change name , have output this:

 1: 'twas brillig, , slithy toves 2:   did gyre , gimble in wabe; 3: mimsy borogroves, 4:   , mom raths outgrabe. 5:             - lewis carroll 

can done using loop or there simpler way this?

you can iterate through each line of poem file , line number using enumerate:

with open('poem.txt') poem_file:     open('poem-numbered.txt', 'w') numbered_file:         index, line in enumerate(poem_file, 1):             numbered_file.write('{}: {}'.format(index, line)) 

the code above first opens original poem file (poem.txt) , opens file writing (hence w second argument open). iterates through lines of original file , writes line output file (poem-numbered.txt) line number.

when passing w second argument open, if file exists, overwritten , if doesn't exist, created.


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -