Home > Net >  Copy string from file to file until one character is found in Python
Copy string from file to file until one character is found in Python

Time:01-16

I have got two text files. I want to read text 1 and look for a string "example", when this string is found I want to copy it together with the next characters until the character "A" is found. For example: Content in text1.txt: "jnajsndneuinnuincuiewexampleohelloAhyhakjs" Content copied in text2.txt: "ejemplohello" The thing is text1 will keep growing and I have to do this task in a loop, so, another restriction is that the second time "example" appears I have to save the second string after it, not the first one ("hello"). Example:

Content in text1.txt:

"jnajsndneuinnuincuiewexampleohelloAhyhakjsexamplegoodbyeAhjuheui"

Content copied in text2.txt:

"ejemplohelloexamplegoodbye"

Any idea of how to do this in Python?

I have tried this code, but it does not work as I want and it does not work once the string has been found one time:

def detect(k):
   string = "example"
   with open("tex1.txt", "r") as f:
      content = f.read()
      if string in content:
         with open("text2.txt", "a ") as f:
            if (character != "A"): 
               f.write(k)

CodePudding user response:

import re
def detect():
    string = "example"
    with open("tex1.txt", "r") as source_file:
      content = source_file.read()
      x = re.split(string, content)
      with open("text2.txt", "a ") as f:
          for index in range(len(x)):
              if index == 0:
                  pass
              else:
                  f.write(string)
                  for char in x[index]:
                      if char == 'A':
                          break
                      else:
                          f.write(char)

re.split will split the entire content from the desired string and store them in a list after that in the outer for loop the initial element of x will be the content before the desired string so it will be passed, the other elements will be processed in the inner loop character by character before reaching "A" in this case.

CodePudding user response:

How about this:

import re

# Initialize variables
example_count = 0
output_string = ""

# Open text1.txt in read mode
with open("text1.txt", "r") as text1:
    # Read the entire file
    text1_content = text1.read()
    # Use regex to find all instances of "example" in the text
    examples = re.finditer("example", text1_content)
    # Iterate through each example
    for example in examples:
        example_count  = 1
        # Get the index of the next character after the example
        next_char_index = example.end()
        # Loop through the rest of the text
        while text1_content[next_char_index] != "A":
            # Add the next character to the output string
            output_string  = text1_content[next_char_index]
            next_char_index  = 1
        # If this is the second instance of "example"
        if example_count == 2:
            # Open text2.txt in write mode
            with open("text2.txt", "w") as text2:
                # Write the output string to text2.txt
                text2.write(output_string)
            break

update: here is for instance updated version that omits index access that might be out of range, and uses global variable instead.

import re

# Initialize global variables
example_count = 0
output_string = ""

# Open text1.txt in read mode
with open("text1.txt", "r") as text1:
    # Read the entire file
    text1_content = text1.read()
    text1_len = len(text1_content)
    # Use regex to find all instances of "example" in the text
    examples = re.finditer("example", text1_content)
    # Iterate through each example
    for example in examples:
        example_count  = 1
        # Get the index of the next character after the example
        next_char_index = example.end()
        # Loop through the rest of the text
        while next_char_index < text1_len and text1_content[next_char_index] != "A":
            # Add the next character to the output string
            output_string  = text1_content[next_char_index]
            next_char_index  = 1
        # If this is the second instance of "example"
        if example_count == 2:
            # Open text2.txt in write mode
            with open("text2.txt", "w") as text2:
                # Write the output string to text2.txt
                text2.write(output_string)
            break
  • Related