【问题标题】:How to print select lines of a text file in python?如何在python中打印文本文件的选择行?
【发布时间】:2015-03-04 19:15:38
【问题描述】:

我有一个包含多行文本的文本文件。每行文本分为两列,以逗号分隔。如何编写程序以仅打印文本文件中第一列具有特定值的行?那么例如我如何编写一个程序来打印第一列有“hello”的每一行?

我正在使用 python 3.3.3

【问题讨论】:

    标签: python-3.x printing text-files line


    【解决方案1】:
    #!/usr/bin/env python3
    import sys
    
    filename = sys.argv[1]
    
    # read the file line by line
    with open(filename) as f:
        for line in f:
            # split the line
            columns = line.split(",")
    
            # print all lines with "hello" as the first column
            if columns[0] == "hello":
                print(line, end='')
    

    【讨论】:

    • 也许缺少任何非代码文本,但我认为它很好(已编辑),应该被接受,所以我将它调回 0。注意:line.split(' ,') 总是返回一个非空列表。
    猜你喜欢
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2017-11-26
    相关资源
    最近更新 更多