-2

I have the following python code whose purpose is to remove blank lines from an input text file. It should return an output file with all blank lines removed but it doesn't. What's the bug? Thank you!

import sys

def main():
    inputFileName = sys.argv[1]
    outputFileName = sys.argv[2]

    inputFile = open(inputFileName, "r")
    outputFile = open(inputFileName, "w")

    for line in inputFile:
        if "\n" in line:
            removeBlank = line.replace("\n", "")
            outputFile.write(removeBlank)
        else:
            outputFile.write(line)

    inputFile.close()
    outputFile.close()

main()
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
Aron Tesfay
  • 313
  • 1
  • 2
  • 11
  • 2
    `outputFile = open(inputFileName, "w")`? – Sneftel Mar 27 '18 at 15:49
  • 1
    Assuming `'\n'` is your newline character (this is OS specific) you're removing all newlines not just blank lines, try taking out your if-else clause and putting `if not line.isspace(): outputFile.write(line)`; also what Sneftel said, write to the correct file – Chris_Rands Mar 27 '18 at 15:49
  • @Chris_Rands Python should take care of any OS issues, but using `isspace()` is a good idea. – John Coleman Mar 27 '18 at 15:55
  • Possible duplicate of [How to delete all blank lines in the file with the help of python?](https://stackoverflow.com/questions/2369440/how-to-delete-all-blank-lines-in-the-file-with-the-help-of-python) – Chris_Rands Mar 27 '18 at 15:55

2 Answers2

0

At present your code appears to truncate its input file immediately after opening it. At best this might give differing results on different platforms. On some platforms the file might be empty. I presume that opening the input file for writing was a typo.

A better way to approach this problem is to use a generator. Also, the correct test for an empty line is line == '\n', not '\n' in line, which will be true for all returned lines except perhaps the last.

def noblanks(file):
    for line in file:
        if line != '\n':
            yield line

You can use this like so:

with open(inputFileName, "r") as inf, open(outputFilename, 'w') as outf:
    for line in noblanks(inf):
        outf.write(line)

The context managers in the with statement will ensure that your files are properly closed without further action on your part.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
0

You have a lot of problem with your code. Specially the condition you check with empty line. People has rightly pointed out some problems.

Here is the solutions that should work and generate the output file with no empty lines.

import sys

def main():
    inputFileName = sys.argv[1]
    outputFileName = sys.argv[2]
    with open(inputFileName) as inputFile, open(inputFileName, "w") as outputFile:

        for line in inputFile.readlines():
            if line.strip() != '':
                outputFile.write(line)

if __name__ == '__main__':
    main()
MaNKuR
  • 2,578
  • 1
  • 19
  • 31