I want to be able to do something like this:
file1 = 'data/f1.txt'
file2 = None
file3 = 'data/f3.txt'
with open(file1) as f1, open(file2) as f2, open(file3) as f3:
for i in range(1000):
x,y,z = func(i)
if f1: f1.write(f"{x}\n")
if f2: f2.write(f"{y}\n")
if f3: f3.write(f"{z}\n")
So that output is only written to files if paths are provided.
I tried the following:
file1 = 'data/f1.txt'
file2 = None
file3 = 'data/f3.txt'
with open(file1) if file1 else None as f1, open(file2) if file2 else None as f2, open(file3) if file3 else None as f3:
for i in range(1000):
x,y,z = func(i)
if f1: f1.write(f"{x}\n")
if f2: f2.write(f"{y}\n")
if f3: f3.write(f"{z}\n")
But I got TypeError: expected str, bytes or os.PathLike object, not NoneType
.
Is there a simple, pythonic way to achieve this?
Thanks.