Searching file for the same string twice and printing both seperately
<p>I am a beginner python programmer with a search question. I need to locate a string of DNA in a DNA file. The issue is that I do not know where the string appears in the file, it appears twice, and I need to know both locations. My current program can only find the first string and I am having difficulty having it continue the search to find the second.  My two ideas that I have have both failed but I think only because I do not understand how to use the functions. Here they are:</p>

<ol>
<li><p>use .seek() to find the first string of DNA I need and set that as the starting point for a second search. My problem is that I do not know exactly where the DNA strings are, so I tried to set my seek location to the DNA string.  This wont work however, as the data needs to be in bytes to find a location, not a string.  I tried to use .index() the location of the DNA string and setting that as a variable, but that also does not work.</p></li>
<li><p>Use .split() to split the DNA text file after the first DNA string was found then running a second search on the right half of the break. I thought this would work, but I only end up with an error reading:</p>

<p>IndexError: list index out of range</p></li>
</ol>

<p>specifically, I am writing .split('str')[1] to use the second half of the string.</p>

<p>Assuming my logic is correct in the program, would these approaches work? Does anyone have a different idea they think I should try? </p>

<p>Thank you for your help and if you need me to clarify anything I can do so.</p>

<p>How large is your file?  If it is not prohibitively long, you could use the naive approach:</p>

<pre><code>file = open("filename.text", r)
genome = file.read()
file.close()
genome_length = len(genome)
pattern = "ATCT" #or whatever your pattern is
pattern_length = len(pattern)
pattern_locations = []
for i in range(genome_length - pattern_length - 1):
    if pattern == genome[i:i+pattern_length]:
        pattern_locations.append(i)
return pattern_locations
</code></pre>

<p>However, if the genome is long then it would require more sophisticated algorithms in order to search in a reasonable time (such as constructing a suffix tree)             </p>

python python-2.7 bioinformatics