Hi,

the problem is that: I have a text file with some lines of text in it. I have to search for a particular line in the file and then copy the lines after the searched line into another text file. This search string comes only once in the text file. I am able to search the line, but can't figure out how to copy the remaining lines into another file.

My code is as shown below:

f = open('testread.txt')
f1 = open('testread1.txt', 'a')

for line in f.readlines():
  if 'this is the line i want to search' in line:
    # here i want to copy all the lines after the searched line in to another file using f1.write()
   
f1.close()
f.close()

Thanks for the help!

Dani AI

Generated

If you only need everything after a unique sentinel line, you can avoid reading the whole file into memory and stream the remainder directly. Stop at the first match, then copy the rest of the file from the current file position to the destination. This is both simple and efficient for large files.

import shutil

target = "this is the line i want to search"

with open("testread.txt", "r", encoding="utf-8") as src, \
     open("testread1.txt", "w", encoding="utf-8") as dst:
    for line in src:
        if target in line:  # use == or startswith if you want an exact match
            break           # do not write the matched line itself
    else:
        raise ValueError("Search string not found")

    shutil.copyfileobj(src, dst)  # copy the remainder efficiently

Notes:

  • Use "w" on the destination if you want to overwrite instead of append.
  • To include the matched line too, write dst.write(line) before copyfileobj.
  • For case-insensitive matches, compare target.lower() to line.lower(), or use re.search for patterns.
  • with ensures files are closed even on errors. See the docs for shutil.copyfileobj and the with statement. An alternative functional approach is itertools.dropwhile with writelines; see itertools.dropwhile.

Recommended Answers

All 3 Replies

Just translate what you think :

f = open('testread.txt')
f1 = open('testread1.txt', 'a')
doIHaveToCopyTheLine=False
for line in f.readlines():
  if 'this is the line i want to search' in line:
    doIHaveToCopyTheLine=True
  if doIHaveToCopyTheLine:
    f1.write(line)
f1.close()
f.close()

Hi,
Thanks for your reply. The code works perfect.

I have used Mid,InStr and other methods to get a substring of a string from one text file and copied the required string to another text file. While I get the correct string, vbscript however generates a BLANK SPACE after evry character in the output string.

I tried to use the Replace function inorder to replace the " " with ""... but the function does not detect any blank spaces at all to replace.

Instead of copying to another file, I even tried to replace the undesired part of the string with a " " and get only the required part ... but then again it gives the same problem[ a BLANK SPACE after evry character]

How do I resolve this issue.

Please help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.