Removing spaces and empty lines from a file Using Python

file, python

Solution

`strip()` removes leading and trailing whitespace characters.

with open("transfer-out/" + file, "r") as f:
    for line in f:
        cleanedLine = line.strip()
        if cleanedLine: # is not empty
            print(cleanedLine)

Then you can redirect the script into a file `python clean_number.py > file.txt`, for example.

Problem

I have a file which contains a value 2000,00. But it contains spaces after 2000,00 and empty lines. I want to remove all the spaces and empty lines, if some one can give some Idea, I ave tried a number of ways but no success. One method I tired is as below ``` # Read lines as a list fh = open("transfer-out/" + file, "r") lines = fh.readlines() fh.close() # Weed out blank lines with filter lines = filter(lambda x: not x.isspace(), lines) # Write "transfer-out/"+file+".txt", "w" fh = open("transfer-out/"+file, "w") #fh.write("".join(lines)) # should also work instead of joining the list: fh.writelines(lines) fh.close() ```

Original source