Home > Software design >  Open a file only once in a for-loop if condition is met
Open a file only once in a for-loop if condition is met

Time:06-07

I have the following Python code:

for i in range(large_number):
  # compute a_i
  if a_i is condition:
    # Need to make change here for the file open
    f = open('file.log', wb)
    # more computations proceeding. Cannot use break

Now that I can achieve opening file only once by

needs_fopen = False
for i in range(large_number):
  # compute a_i
  if a_i is condition:
    needs_fopen = True

if needs_fopen is True:
  f = open('file.log', wb)

I do not want to do the second approach due to my code complexity. How to achieve the first method but open the file only once if the condition is satisfied?

CodePudding user response:

f = None
for i in range(large_number):
  # comput a_i
  if a_i is condition and not f:
    f = open('file.log', wb)

CodePudding user response:

Use any() with a generator comprehension:

if any(i is condition for i in range(number)):
  f = open('file.log', wb)
  • Related