Home > front end >  writing a program to copy source file to target file and remove empty lines then output total empty
writing a program to copy source file to target file and remove empty lines then output total empty

Time:05-05

I am trying to write a python program where;

  • user enters the source file to read and the target file to write.
  • Copy contents from the source file to the target file.
  • Remove empty extra lines.
  • output the number of empty lines that were removed.

I currently have written code to perform this but cant work out how to output the total number of empty lines that were removed. Could someone please explain what I am doing wrong?

f1 = open(input("Source file name: "))
f2 = open(input("Target file name: "), mode = 'w')
for line in f1:
    if not line.strip(): continue
    f2.write(line)

f1.close()
f2.close()
print("lines removed:")

output should be as followed

source file name : string.txt
target file name: string_empty.txt
lines removed : 15

CodePudding user response:

You can introduce a counter variable into your for loop, so that each time you do not copy a line it increases by 1:

count = 0 #counter variable
for line in f1:
    if not line.strip():
        count  = 1
        continue
    f2.write(line)

f1.close()
f2.close()
print("lines removed:", count)
  • Related