JobyB
JobyB

Reputation: 21

How do you format a text file after copy/pasting it from another text file?

I am using python and at the moment I can copy text from one text file to another. However I need to be able to take the text and and number each line of text. At this point I'm not sure how to insert more text after copying the text.

    with open("copyTo.txt", "w") as f1:
         for line in f:
             f1.write(line)

For example if I write: "Hello everyone! My name is Bob. It's a nice day today." I expect the outcome to look like this:

  1. Hello everyone!
  2. My name is Bob.
  3. It's a nice day today.

Upvotes: 1

Views: 219

Answers (1)

You can easily do it with f-string and enumerate like below.

with open("copyTo.txt", "w") as f1:
    for index,line in enumerate(f,start=1):
        f1.write(f'{index}. {line}')

Here you are enumerating the lines by assigning the start index to 1. Then using f-string you can format the string according to your wish and write to the output file.

Upvotes: 1

Related Questions