1、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()
2、运行前后文件的对比:
有空行的文件:
运行代码生成无空行的文件: