2016-09-22 9 views
0

条件に応じてファイルを開き、ファイルを読み込みます。私は次のスクリプトレットを書いた:条件付きのPythonファイルを開きますが、1つのファイルからデータを読み込みます

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) 

は、私は何度も何度も繰り返し同じライン(10 LINE3)を書く/繰り返す必要はありません適切な神託の方法は、ありますか?ありがとう!

+0

あなたは関数を作っただけで、ファイルを開くために別の関数を作るのはなぜですか? – MooingRawr

+1

2つのコードはまったく同じです。とにかく同じコードを実行すると、あなたの '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) 

いずれか、またはコードを間違えてコピーしました。大文字小文字に応じて何か違うことをしたい場合は、その引数を取る関数を作るか、条件文をまず実行して、それを使って特定の文字列や値を設定します。

など。

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) 
関連する問題