【问题标题】:how to print from a particular line from text file in python如何从python中的文本文件的特定行打印
【发布时间】:2020-05-11 07:22:05
【问题描述】:

我正在使用此代码搜索一个特定的字符串:

stringToMatch = 'blah'
matchedLine = ''
#get line
with open(r'path of the text file', 'r') as file:
    for line in file:
        if stringToMatch in line:
            matchedLine = line
            break
#and write it to the file
with open(r'path of the text file ', 'w') as file:
    file.write(matchedLine)

即使字符串出现多次,它也只会打印一次。我还想在出现特定单词后打印所有行。我该怎么做?

【问题讨论】:

  • 您的break 说一旦找到一个案例就离开for loop。您可能需要删除/修改它。

标签: python python-3.x text


【解决方案1】:

设置一个标志以跟踪您何时看到该行,并将这些行写入同一循环中的输出文件。

string_to_match = "blah"
should_print = False
with open("path of the text file", "r") as in_file, open("path of another text file", "w") as out_file:
    for line in in_file:
        if string_to_match in line:
            # Found a match, start printing from here on out
            should_print = True
        if should_print:
            out_file.write(line)

【讨论】:

    【解决方案2】:
    stringToMatch = 'blah'
    matchedLine = ''
    
    # get line
    lines = ''
    match = False
    with open(r'path of the text file', 'r') as file:
        for line in file:
            if match:
                # store lines if matches before
                lines += line + '\n'
            elif stringToMatch in line:
                # If matches, just set a flag
                match = True
    
    # and write it to the file
    with open(r'path of the text file ', 'w') as file:
        file.write(lines)
    

    【讨论】:

      【解决方案3】:

      你可以像这样修改你的代码:-

      stringToMatch = 'blah'
      matchedLine = ''
      #get line
      with open(r'path of the text file', 'r') as file:
          for line in file:
              if stringToMatch in line:
                  matchedLine += line + '\n'
      
      #and write it to the file
      with open(r'path of the text file ', 'w') as file:
          file.write(matchedLine)
      

      希望你明白了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多