'writing a program to copy source file to target file and remove empty lines then output total empty lines removed

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


Solution 1:[1]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lolrenz Omega