如何从此文件中删除空行?

时间:2017-01-12 16:50:33

标签: 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[(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)

我想从文件中删除空行,但没有任何反应。

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

1 个答案:

答案 0 :(得分:2)

试试这个:

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):

sed -i '/^\s*$/d' foo.txt