-1

I have this file called foo.txt and it has the following content:

# [empty line here]
bar 12
baz 34

the empty line is caused by removing everything in that line, here is the code:

newdict = {}
with open('foo.txt','r') as f:
    for line in f:
        if line.isalpha() == True: 
            splitline = line.split( )
            newdict[(splitline[0])] = ",".join(splitline[1:])
removethis = raw_input("Item to be removed: ")
if removethis in newdict:
    with open('foo.txt','r') as f:
        f.read()
    new = new.replace(removethis, '')
    with open('foo.txt','w') as f:
        f.write(new)
    with open('foo.txt','rw') as g:
        for line in g:
            if not line.isspace():
                g.write(line)

I want to remove the empty line from the file but nothing happens.

EDIT: To someone who marked this as duplicate, no thanks I don't want regex

1 Answers1

2

Try this:

with open('data/aa', 'rw') as f, open('data/aa2', 'w') as f2:
    newf = [a for a in f if a.strip()]
    f2.writelines(newf)

Or you can do it with sed as well (if you are on linux):

sed -i '/^\s*$/d' foo.txt
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78