open conditional python files but read data from one
<p>I want to open and read a file depending on a condition, read only if condition met true. I wrote the following scriptlet: </p>

<pre><code>def bb(fname, species):
     if species in ('yeast', 'sc'):
         pm =  open('file.txt', 'rU')
         for line in pm:
             line = line.split()
             with open(fname, 'rU') as user:
                 for e in user:
                     e = e.split()
                     if e[0] in line:
                         print(line)
    elif species in ('human', 'hs'):
         pm =  open('file2.txt', 'rU')
         for line in pm:
             line = line.split()
             with open(fname, 'rU') as user:
                 for e in user:
                     e = e.split()
                     if e[0] in line:
                         print(line)
</code></pre>

<p>Is there a proper pythonic way, where I don't have to repeat/write the same lines (line3 to 10) over and over again ? Thanks ! </p>

<p>Since you seem to be doing the exact same thing regardless of the condition, you could just collapse everything? </p>

<pre><code>def bb(fname, species):
     if species in ['yeast', 'sc', 'human', 'hs']:
         pm =  open('file.txt', 'rU')
         for line in pm:
             line = line.split()
             with open(fname, 'rU') as user:
                 for e in user:
                     e = e.split()
                     if e[0] in line:
                         print(line)
</code></pre>

<p>Either that or you've made a mistake copying the code. If you want to do something different depending on the case, then you could make a function that takes that argument, or do the conditional statement first and use it to set a certain string or value. </p>

<p>E.g. </p>

<pre><code>if species in ('yeast', 'sc'):
    permissions = 'rU'
</code></pre>

<p>etc.</p>

<hr>

<p>Edit: Ah, with your edited question the answer would be as above but then </p>

<pre><code>if species in ('yeast', 'sc'):
    file_name = 'file.txt'
elif species in ('human', 'hs'):
    file_name = 'file2.txt'
</code></pre>

python file if-statement