3

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.

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??

1
  • You just need a flag in your code to do this. For the simple requirement you can just use sed -n '/3/,$p' to print out all the lines after a line contains "3". Commented Dec 26, 2013 at 6:27

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Please, no camels! It's Python (thanks god), not C or (god forbid) Java
Changed just for you <3
2
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)

Comments

1

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:

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.

1 Comment

This is an answer to a may be similar, but indeed different question. For OP's question storing ranges of lines (including all their text) is absolute overkill. Better ask your own question, add your answer there, and, if you think that it is related to this question, link to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.