Reputation: 388
I am trying to define a function so that it includes only part of a with statement. For example, it would include the section cut off by #####.
#####
with open(filename,'r') as fh:
contentall = fh.read().replace('\n', '')
contentall = contentall.upper()
print contentall
#####
i = contentall.count(">")
print i
My problem is that there is still some stuff in the with
statement that I don't want in my function. Can this be done without creating two different with
statements?
Upvotes: 0
Views: 55
Reputation: 166
You could use a variable to enable or disable the counting behaviour:
def contentFunc(filename, countBool):
with open(filename, 'r') as fh:
contentall = fh.read().replace('\n',' ').upper()
print contentall
if countBool == True:
print contentall.count(">")
Upvotes: 0
Reputation:
Could you not do this
def getContent(filename):
with open(filename,'r') as fh:
contentall = fh.read().replace('\n', '')
contentall = contentall.upper()
return contentall
contentall = getContent(filename)
print contentall
i = contentall.count(">")
print i
Upvotes: 2
Reputation: 9986
No. You could pass the context manager to the second function as a parameter, but you can't share a context manager between two function definitions.
Upvotes: 2