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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!