I want to open and read a file depending on a condition, read only if condition met true. I wrote the following 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)
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 !
You can put the filename value in a variable
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)
or define another function
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)
Since you seem to be doing the exact same thing regardless of the condition, you could just collapse everything?
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)
Either that or you've made a mistake copying the code. If you want to do something different depending on the case, then you could make a function that takes that argument, or do the conditional statement first and use it to set a certain string or value.
Eg
if species in ('yeast', 'sc'):
permissions = 'rU'
etc.
Edit: Ah, with your edited question the answer would be as above but then
if species in ('yeast', 'sc'):
file_name = 'file.txt'
elif species in ('human', 'hs'):
file_name = 'file2.txt'
Just put opening of file in if else
case rest will be done in a similar manner and same code block as well.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.