2

The following code work but it's little bit messy and most of IDE show an error for undefined variable => "myFile" even if the code works.

i = 0
block = False
while i < 10:
   if block == True:
      myFile.write("End of a Turn.")
   block = True
   myFile = open("path/of/my/file/"+str(i)+".txt", "w")
   myFile.write("The turn begin.")
   i += 1

What I want to do is to "pre-define" the variable before the first assignment:

#myFile = SOMETHING_THAT_DOES_NOT_RUIN_THE_FOLLOWING_CODE
myFile = None #RESOLVE
i = 0
block = False
while i < 10:
   if block == True:
      myFile.write("End of a Turn.")
   block = True
   myFile = open("path/of/my/file/"+str(i)+".txt", "w")
   myFile.write("The turn begin.")
   i += 1

To avoid some IDE comprehension problems.

Ty for help,

S.

0

1 Answer 1

1

You can do it like this.

myFile = None
i = 0
block = False
while i < 10:
   if block and myFile:
       # ...

Or, probably cleaner:

for i in range(9):
    with open(str(i) + '.txt', 'w') as myFile:
        myFile.write('The turn begin. End of a turn')
with open(str(i + 1) + '.txt', 'w') as myFile:
        myFile.write('The turn begin.')
Sign up to request clarification or add additional context in comments.

1 Comment

@user3675596 I added an alternative version. You can get rid of the block variable, also manually incrementing i is not necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.