python批量删除文件中多余的空行

1、需要处理的文件poem1.txt (样例)

# cat poem1.txt 
01

03

05




10

2、执行python脚本delete_nullRow.py

# cat delete_nullRow.py 
# coding = utf-8
def clearBlankLine():
    file1 = open('poem1.txt', 'r', encoding='utf-8') # 要去掉空行的文件 
    file2 = open('poem2.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()

3、批量删除空行后生成的新文件poem1.txt

# cat poem2.txt 
01
03
05
10

你可能感兴趣的:(大数据运维工作经验,python)