0

I would like to accept a certain number (limited to - say, 3) to evaluate a condition within the a with statement. I did find it's possible to do something like this. Can I do something similar to the following in the with statement by evaluating a condition:

def foo(num):
    with open("1.txt","a") as f1, open("2.txt") as f2 <<if num >= 2>>, open("3.txt") as f3 <<if num >= 3>>:
        if num >= 1:
            f1.write("1")
            if num >= 2:
                f2.write("2")
                if num >= 3:
                    f3.write("3")

Is this possible? Is there any other way I can evaluate an if condition for the objects involved in a with statement so that I use exactly the same number of objects as in num?

P.S. : This code above is just an example using files, it can be replaced by objects too.

9
  • @reportgunner It is not. I'm aware of that. More interested in the condition I've marked within << >>. Commented Jul 3, 2019 at 8:55
  • Why do you absolutely want a with statement? I feel like it would be easier to just manually open and close the files here Commented Jul 3, 2019 at 8:55
  • @Nakor With allows me not to close the files explicitly. Commented Jul 3, 2019 at 8:56
  • 2
    How does this not help?! You make a list of files and iterate over them. Commented Jul 3, 2019 at 8:57
  • 2
    @skrowten_hermit your example is very arbitrary. We don't know what is the relationship between f1 f2 and f3 and we don't know what is the reason you insist on using with statement like this. Why don't you do the logic first, store the result in a variable and then work with files as required ? (even one by one ?) Commented Jul 3, 2019 at 9:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.