Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing spaces and empty lines from a file Using Python

Tags:

python

file

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()
like image 980
Sara Avatar asked May 29 '12 06:05

Sara


People also ask

How do you remove blank spaces in a text file in Python?

Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

How do you strip a file in Python?

Use str. rstrip or str. lstrip to strip space from right or left end only.


2 Answers

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.

like image 195
Jill-Jênn Vie Avatar answered Nov 14 '22 13:11

Jill-Jênn Vie


Another one with list comprehension:

clean_lines = []
with open("transfer-out/" + file, "r") as f:
    lines = f.readlines()
    clean_lines = [l.strip() for l in lines if l.strip()]

with open("transfer-out/"+file, "w") as f:
    f.writelines('\n'.join(clean_lines))
like image 32
Diego Navarro Avatar answered Nov 14 '22 12:11

Diego Navarro