Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading