python怎么过滤掉空行?

2025-12-02 0 43,226

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、运行前后文件的对比:

有空行的文件:

p7.jpg

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

p6.jpg

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 常见问题 python怎么过滤掉空行? https://www.zhiup.top/6896.html

相关