Python 如何从该文件中删除空行?

Python 如何从该文件中删除空行?,python,Python,我有一个名为foo.txt的文件,它有以下内容: # [empty line here] bar 12 baz 34 空行是由于删除该行中的所有内容而导致的,下面是代码: newdict = {} with open('foo.txt','r') as f: for line in f: if line.isalpha() == True: splitline = line.split( ) newdict[(split

我有一个名为
foo.txt
的文件,它有以下内容:

# [empty line here]
bar 12
baz 34
空行是由于删除该行中的所有内容而导致的,下面是代码:

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)
我想从文件中删除空行,但什么也没发生

编辑:对于将此标记为重复的人,不,谢谢我不想要正则表达式

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)

或者您也可以使用sed(如果您在linux上):


执行
new.replace('\n\n','\n')
您必须关闭文件!!!f、 close()@wonka我以为“with as”会自动关闭it@user7091717你说得对。它会自动关闭,你到底想做什么?我还是有点不清楚。你只是想知道如何从文件中删除空行吗?你能解释一下sed和“/^\s*$/d”是什么意思吗?@user7091717你在linux上吗?如果a.strip()是什么意思?它不需要一些条件吗?.strip()是否也会删除空格和行分隔?如果执行
a.strip()
操作,则只包含空格的行将得到空字符串。空字符串被视为false,将跳过这些行
.strip()
删除字符串两端的空白。
sed -i '/^\s*$/d' foo.txt