Skip to content

Instantly share code, notes, and snippets.

@Keinta15
Created September 19, 2019 23:33
Show Gist options
  • Save Keinta15/949fb58fe52cc62e72713c3597dae42f to your computer and use it in GitHub Desktop.
Save Keinta15/949fb58fe52cc62e72713c3597dae42f to your computer and use it in GitHub Desktop.
Remove blank lines from a .txt file
# Before checking we strip leading and trailing characters
# Check if the line is not empty
with open("empty.txt", 'r') as inp, open('out.txt', 'w') as out:
for line in inp:
if line.strip():
out.write(line)
# Before checking we strip only trailing characters
# Check if the line is not empty
with open("empty.txt", 'r') as inp, open('out.txt', 'w') as out:
for line in inp:
if line.rstrip():
out.write(line)
# Check if the length is greater than zero
with open("empty.txt", 'r') as inp, open('out.txt', 'w') as out:
for line in inp:
if len(line.strip()) > 0:
out.write(line)
# Check if the line is not a new line
with open("empty.txt", 'r') as inp, open('out.txt', 'w') as out:
for line in inp:
if line != '\n':
out.write(line)
# Check if the line is not a space using a built in function
with open("empty.txt", 'r') as inp, open('out.txt', 'w') as out:
for line in inp:
if not line.isspace():
out.write(line)
# Check if the line is not white space using regular expressions
import re
with open("empty.txt", 'r') as inp, open('out.txt', 'w') as out:
for line in inp:
if re.search('\S', line):
out.write(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment