以下代码可以工作,但是有点混乱,即使代码可以工作,大多数IDE也会显示未定义变量=>“ myFile”的错误。

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


我想做的是在第一次分配之前“预定义”变量:

#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


为了避免一些IDE理解问题。

求助,

S.

最佳答案

你可以这样

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


或者,可能更干净:

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.')

关于python - 如何预定义python变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24011945/

10-12 22:07