您的当前位置:首页正文

Python去掉文件中空行

来源:花图问答
# coding = utf-8
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()

有空行的文件:


有空行的文件

运行代码生成无空行的文件:


无空行的文件