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.

skrowten_hermit
  • 437
  • 3
  • 11
  • 28
  • @reportgunner It is not. I'm aware of that. More interested in the condition I've marked within << >>. – skrowten_hermit Jul 03 '19 at 08: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 – Nakor Jul 03 '19 at 08:55
  • @Nakor With allows me not to close the files explicitly. – skrowten_hermit Jul 03 '19 at 08:56
  • 2
    How does [this](https://stackoverflow.com/a/4617069/476) *not* help?! You make a *list of files* and iterate over them. – deceze Jul 03 '19 at 08:57
  • @deceze I have updated the post to avoid any confusion. – skrowten_hermit Jul 03 '19 at 09:01
  • 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_ ?) –  Jul 03 '19 at 09:02
  • @skrowten_hermit I think your questions lies on the syntax definition of the `with` statement. Your construction is not syntactically correct. More info [here](https://docs.python.org/3/reference/compound_stmts.html#with) – Layo Jul 03 '19 at 09:04
  • `files = ['%d.txt' % i for i in range(1, num + 1)]` – That's your list of files. Then you do the [`ExitStack` way of opening them](https://stackoverflow.com/a/4617069/476). Then you do `for i, file in enumerate(files, 1): file.write(i)`. That's the way to do this with a dynamic number of files. No nested or inline `if` statements needed. – deceze Jul 03 '19 at 09:06
  • @Layo Okay. I did go through that. I just wanted to know if I could do something like [this](https://stackoverflow.com/questions/27803059/conditional-with-statement-in-python). So that I can declare only those many objects as required or defined by the variable `num`. – skrowten_hermit Jul 03 '19 at 09:09

0 Answers0