我想根据条件打开并读取文件,只有在条件满足时才读取。我写了下面的scriptlet:
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 :(得分: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)
答案 1 :(得分: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'
答案 2 :(得分: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)