Searching number of times a string (from file a) occurs in file b. Each string from file a is on a separate line
<p>I am a not new in Python but I am not an educated programmer and I use it very often for my work. So sorry in advance for any not elegant coding solutions. </p>

<p>I have a file (.txt) with a unique string on each line. I want to know how many times each string occurs in another file. I build the following, which works as long as I feed the text I want to find "2-177-382":</p>

<pre><code>count = 0
with open(Input_file_B) as f:
    for line in f:
        count += line.count("2-177-382")
    print count
</code></pre>

<p>This results in:</p>

<pre><code>Number of times: 19
</code></pre>

<p>So far so good. When I replace it with a variable it also works.</p>

<pre><code>y="2-177-382"
count = 0
with open(Input_file_B) as f:
    for line in f:
        count += line.count(y)
    print count
</code></pre>

<p>This also works and results also in:</p>

<pre><code>Number of times: 19
</code></pre>

<p>But now I want to fill <em>y</em> using a loop with the data extracted from file A, this is where it goes wrong. File A looks like this:</p>

<pre><code>1-1-24
1-1-25
1-1-26
1-1-27
14-178-370
5-224-309
5-226-307
2-177-382
</code></pre>

<p>I show this as an example below (without how I extract it from the other file). </p>

<pre><code>total_A = open(Input_file_A,'r')
Data_input_file_A = total_A.readlines()
y = Data_input_file_A[7]
print y
</code></pre>

<p>Results in: </p>

<pre><code>2-177-382
</code></pre>

<p>Exactly the same as before and also a string, when I feed this into the earlier code:</p>

<pre><code>total_A = open(Input_file_A,'r')
Data_input_file_A = total_A.readlines()
y = Data_input_file_A[7]
count = 0
with open(Input_file_B) as f:
    for line in f:
        count += line.count(y)
    print count
</code></pre>

<p>Result:
    Number of times: 0</p>

<p>How is this possible, please help me out!?</p>

<p><code>readlines()</code> does not remove the newline character. This should be clear if instead of <code>print y</code> you do <code>repr (y)</code> to reveal all the characters. So in your code you need:</p>

<pre><code>y = Data_input_file_A[7].rstrip()
</code></pre>

python search