File Handling A) Count The Number of Lines in The Given File

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

10.

File Handling

a) Count the number of lines in the given file.


fname = input("Enter file name: ")
nlines = 0
with open(fname, 'r') as f: #(or) f= open(fname, 'r')
for line in f:
nlines += 1
print("Number of lines:",nlines)

b) Copy the contents of file1 to file2 and display the contents of both on the
screen.
with open("test.txt") as f1:
print ("Contents of File 1:\n",f1.read())
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
with open("out.txt") as f2:
print ("Contents of File 2 after copying File 1:\n",f2.read())

You might also like