python remove empty lines from file
with open("new_file","r") as f:
for i in f.readlines():
if not i.strip():
continue
if i:
print i,
3.78
9
import os
def remove_empty_lines(filename):
if not os.path.isfile(filename):
print("{} does not exist ".format(filename))
return
with open(filename) as filehandle:
lines = filehandle.readlines()
with open(filename, 'w') as filehandle:
lines = filter(lambda x: x.strip(), lines)
filehandle.writelines(lines)
Thank you!
9
0
3.57
7
with open(fname, 'r+') as fd:
lines = fd.readlines()
fd.seek(0)
fd.writelines(line for line in lines if line.strip())
fd.truncate()
Thank you!
7
0
Are there any code examples left?
New code examples in category Python