2016-09-22 84 views
0

我想根據條件打開並讀取文件,只有條件符合條件時才能讀取。我寫了下面的腳本:打開條件python文件,但從中讀取數據

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) 

是否有正確的pythonic的方法,在這裏我沒有重複/寫同一線(3號線至10)一遍又一遍?謝謝 !

+0

你做了一個函數,爲什麼不打開另一個只是打開文件? – MooingRawr

+1

這兩段代碼完全相同。無論如何,如果你運行相同的代碼,你的'if'有什麼意義呢? –

回答

0

你可以把文件名值的變量

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) 

或定義另一個函數

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) 
0

因爲你似乎不管條件如何的在做同樣的事情,你可以只崩潰一切?

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) 

無論是你還是你犯了一個錯誤複製代碼。如果你想根據情況做一些不同的事情,那麼你可以創建一個接受該參數的函數,或者首先執行條件語句並使用它來設置特定的字符串或值。

E.g.

if species in ('yeast', 'sc'): 
    permissions = 'rU' 


編輯:啊,你編輯的問題的答案將是如上但隨後

if species in ('yeast', 'sc'): 
    file_name = 'file.txt' 
elif species in ('human', 'hs'): 
    file_name = 'file2.txt' 
0

只要把文件打開在if else情況下,其餘的將是以類似的方式和相同的代碼塊完成。

def bb(fname, species): 
    if species in ('yeast', 'sc'): 
      pm = open('file.txt', 'rU') 
    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)