Removing spaces and blank lines from a file Using Python

I have a file that contains a value of 2000.00.

But it contains spaces after 2000.00 and blank lines.

I want to remove all spaces and empty lines, if someone can give some idea, I tried several ways, but did not succeed.

One of the ways I'm tired is 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() 
+4
source share
5 answers

strip() removes leading and trailing whitespace.

 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 to the python clean_number.py > file.txt file python clean_number.py > file.txt , for example.

+5
source

Another with a list:

 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)) 
+2
source

Change the 'lines' line to use the next generator, and it should do the trick.

 lines = (line.strip() for line in fh.readlines() if len(line.strip())) 
+2
source

This should work as you wish:

 file(filename_out, "w").write(file(filename_in).read().strip()) 

EDIT: Although the previous code works in python 2.x, it does not work python 3 (see @gnibbler comment). For both versions, use this:

 open(filename_out, "w").write(open(filename_in).read().strip()) 
+1
source

Functional:)

 import string from itertools import ifilter, imap print '\n'.join(ifilter(None, imap(string.strip, open('data.txt')))) # for big files use manual loop over lines instead of join 

Using:

 $ yes "2000,00 " | head -n 100000 > data.txt $ python -c "print '\n'*100000" >> data.txt $ wc -l data.txt 200001 data.txt $ python filt.py > output.txt $ wc -l output.txt 100000 output.txt 
0
source

Source: https://habr.com/ru/post/1414824/


All Articles