LearnFrenzy
Sign in Take a free test

File Handling · File Handling Coding Problems · Question 4

Copy a file adding line numbers in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Copy a source file to a new file, numbering every line, then print the new file.

Solution
main.py Run
import os, tempfile
os.chdir(tempfile.mkdtemp())
with open("hello.py", "w") as f:
    f.write('name = "Asha"\nprint("Hi", name)\n')

with open("hello.py") as src, open("hello_numbered.txt", "w") as dst:
    for no, line in enumerate(src, 1):
        dst.write(f"{no:>3}: {line}")

with open("hello_numbered.txt") as f:
    print(f.read(), end="")

Output Verified by running it on Python 3

  1: name = "Asha"
  2: print("Hi", name)

One with statement can open two files. Each line already ends with "\n", so none is added.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links