2016-09-22 82 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)