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>You can put the filename value in a variable</p>

<pre><code>def bb(fname, species):
    if species in ('yeast', 'sc'):
        fname2 = 'file.txt'
    elif species in ('human', 'hs'):
        fname2 = 'file2.txt'
    else:
        raise ValueError("species received illegal value")

    with  open(fname2, 'rU') as pm:
        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>or define another function</p>

<pre><code>def bb(fname, species):
    if species in ('yeast', 'sc'):
        read_file('file.txt', fname)
    elif species in ('human', 'hs'):
        read_file('file2.txt', fname)

def read_file(fname1, fname2):
    with  open(fname1, 'rU') as pm:
        for line in pm:
            line = line.split()
            with open(fname2, 'rU') as user:
                for e in user:
                    e = e.split()
                    if e[0] in line:
                        print(line)
</code></pre>

python file if-statement