简体   繁体   English

在python中找到某个字符串后如何打印所有行?

[英]How to print all the lines after it found certain string in python?

I have following lines in a file. 我在文件中有以下几行。 I want to read the file after it found certain string. 找到特定字符串后,我想读取文件。

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

Here if the string "3" is found i want to copy all the lines after this into a another file. 在这里,如果找到字符串“ 3”,我想将其后的所有行复制到另一个文件中。

My output should be: 我的输出应为:

This is 3rd line
This is 4th line
This is 5th line in another file.

My code is: 我的代码是:

file1=open("file1.txt","r")
file2=open("file2.txt","w")
line=fo.readlines()
  for line in lines:
      if "3" in line:
         print line
         file2.write(line)

It print only this line alone "This is 3rd line" Its not printing all the lines after this line?? 它仅单独打印此行“这是第三行”,而不打印此行之后的所有行?

This is the sort of question a complete beginner would ask, so I'm going to break it down a bit, please don't feel insulted. 这是一个完整的初学者会问的问题,所以我将其分解,请不要感到侮辱。

You need to introduce a state into your program. 您需要在程序中引入状态。 This state will tell the loop whether it's always printing or not, you can do this via setting a variable like so: 此状态将告诉循环是否一直在打印,您可以通过设置变量来做到这一点,如下所示:

file1 = open("file1.txt","r")
file2 = open("file2.txt","w")
always_print = False
lines = fo.readlines()
for line in lines:
  if always_print or "3" in line:
     print line
     file2.write(line)
     always_print = True

The key is your program can be in two states, one where you've found the line you care about, and one where you haven't found it yet. 关键是您的程序可以处于两种状态,一种状态是您已找到所关注的行,另一种状态是尚未找到它。 And the way you represent this is by using variables. 您使用变量来表示的方式。 And by checking that variable you can determine whether or not you should perform any particular action. 通过检查该变量,您可以确定是否应该执行任何特定操作。

Hope this isn't too confusing. 希望这不会太令人困惑。

print_flag = False
for line in lines:
    if "3" in line:
        print_flag = True
    if print_flag:
        file2.write(line)

EDIT: A little more sophisticated solution (just as an intellectual excercise): 编辑:一个更复杂的解决方案(就像一个知识锻炼):

line_iter = iter(lines)

for line in line_iter:
    if "3" in line:
        break
else:
    raise 'Target line not found'
file2.write(line)
for line in line_iter:
    file2.write(line)

I needed something similar, but instead of printing all the lines i needed just several lines until a certain stop condition for each occurrence (if you want to print/get all until EOF just set none end condition: 我需要类似的东西,但是我不需要打印所有的行,而是只需要几行,直到每次出现的特定停止条件为止(如果要打印/获取所有内容,直到EOF都没有设置结束条件:

def find_occurences(file1_path, catch_start, catch_end):
    results = []
    with open(file1_path, 'r') as f1:
        lines = f1.readlines()
    i = 0
    while i < len(lines):
        if catch_start in lines[i]:
            for j in range(i + 1, len(lines)):
                if catch_end in lines[j] or j == len(lines)-1:
                    results.append(lines[i:j])
                    i = j
                    break
        else:
            i += 1
    return results

Then if you want to print or write them into another file you have occurrences as lists within a list and you can break it down or otherwise use it in the calling function. 然后,如果要打印或将它们写入另一个文件,则列表中的列表会出现这些列表,您可以将其分解或在调用函数中使用它。

    for result in find_occurrences(path, start_c, end_c):
        for line in result:
            print str(line)
            with open(file_path, 'a') as f:
                f.write(str(line))

Also if you are writing to file per line you probably want to use 'a' and not 'w' because 'w' would replace any existing file content. 同样,如果您要按行写入文件,则可能要使用“ a”而不是“ w”,因为“ w”将替换任何现有文件内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Python中的某些行之后仅打印行 - Print only lines after certain lines in Python 匹配在python中找到的字符串之后打印一些前面的行 - Print a number of previous lines after matching string found in line in python 如何在 Python 中打印包含某个字符串的文本文件的行? - How to print the lines of a text file that contain a certain string in Python? 在 python 中,如何打印不包含某个字符串的行,而不是打印包含某个字符串的行: - In python, how can I print lines that do NOT contain a certain string, rather than print lines which DO contain a certain string: Python,将文件中具有特定字符串的所有行添加到列表中,然后随机选择要打印的字符串? - Python, Adding all lines with a certain string from a file to list then randomly choosing which string to print? Python - 如何删除某个字符串第一次出现之前的所有行 - Python - How to remove all the lines before the first occurrence of a certain string 如何在Python中打印出文件中的某些行 - How to print out certain lines in a file in Python 如何在文件中打印具有一定长度的行(Python) - How to print lines with a certain length in a file(Python) 在python中匹配字符串后如何打印所有字符串 - How to print all the string after matching a string in python Python在一定数量的空行后打印文本 - Python Print text after certain number of blank lines
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM