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()
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.
Use str. rstrip or str. lstrip to strip space from right or left end only.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With