File Handling 8: copy first n lines of a file, copy from nth line to mth line in a file

# Copy first n lines of a file

fs = open("ipt.txt", "r")
fd = open("opt.txt", "w+")

nlines = int(input("Enter number of lines to copy : "))
counter = 0

while(True):
if(counter == nlines):
break

Line = fs.readline()

if not Line:
break

fd.write(Line)
counter += 1

print("file copied")


print("displaying copied file:")
fd.seek(0,0)
while(True):
Line = fd.read()
if not Line:
break
print(Line)

fs.close()
fd.close()


# Copy first n lines of a file

fs = open("ipt.txt", "r")
fd = open("opt.txt", "w+")

nlines = int(input("Enter number of lines to copy : "))

L = fs.readlines()
for Line in L[0:nlines]:
fd.write(Line)

print("file copied")

print("displaying copied file:")
fd.seek(0,0)

L = fd.readlines()
for Line in L:
print(Line)

fs.close()
fd.close()


No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu