Python 去掉文本中空行

pandas 操作csv文件时,一直报错,排查后发现csv文本中存在很多“空行”:

 

So 需要把空行全部去掉:

def clearBlankLine():
    file1 = open('text1.txt', 'r', encoding='utf-8') # 要去掉空行的文件 
    file2 = open('text2.txt', 'w', encoding='utf-8') # 生成没有空行的文件
    try:
        for line in file1.readlines():
            if line == '\n':
                line = line.strip("\n")
            file2.write(line)
    finally:
        file1.close()
        file2.close()


if __name__ == '__main__':
    clearBlankLine()

根据上面代码即可实现。

 

补充:

  代码中用都是 open(), 可改为 with open()as  f:  形式,省去手动 close。

 

posted @ 2018-08-01 12:48  ZhuGaochao  阅读(4060)  评论(0编辑  收藏  举报