with open('letternumber.txt', 'w') as file:
k=4
C = ['or'.join([' I{}.output '.format(i) for i in range(0, k)])]
F = list(' C{}.input'.format(i) for i in range (0,k))
for j in C:
for i in F:
x=''.join(i ' :=' j)
print(x)
file.write(x)
I get the output as:
C0.input := I0.output or I1.output or I2.output or I3.output
C1.input := I0.output or I1.output or I2.output or I3.output
C2.input := I0.output or I1.output or I2.output or I3.output
C3.input := I0.output or I1.output or I2.output or I3.output
but I am not able to write into the file.
CodePudding user response:
Your identations are not correct. The loops and the write operation are outside of the with
block.
Try this instead:
with open('letternumber.txt', 'w') as file:
k=4
C = ['or'.join([' I{}.output '.format(i) for i in range(0, k)])]
F = list(' C{}.input'.format(i) for i in range (0,k))
for j in C:
for i in F:
x=''.join(i ' :=' j)
print(x)
file.write(x)
Keep also in mind that you are continuosly overwriting the value of x
, so be careful with that if you want to write every single combination to the file.
CodePudding user response:
Fix the indentation for the for loops and the file.write(x)
statement.
The with statement automatically closes the opened "file" once the end of the with block is reached. Any attempt to access "file" after the with block will result in an "I/O operation on closed file" error.
with open('letternumber.txt', 'w') as file:
k=4
C = ['or'.join([' I{}.output '.format(i) for i in range(0, k)])]
F = list(' C{}.input'.format(i) for i in range (0,k))
for j in C:
for i in F:
x=''.join(i ' :=' j)
print(x)
file.write(x '\n')