• 技术文章 >常见问题 >Python常见问题

    python怎么过滤掉空行?

     Ly Ly2020-05-25 15:19:11原创5643

    1、python过滤掉空行的代码:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    # 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

    专题推荐:python
    上一篇:python什么等价于True? 下一篇:python如何取余和取商?

    相关文章推荐

    • python怎么筛选列表中大于0的数据?• python怎么判断库是否安装?• python怎么让数字右对齐?• python是一种编程语言吗?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网