请问:why 出错

请问:why 出错

#copy file
def copyFile(oldFile, newFile):
    f = open(oldFile, "r")
    f2 = open(newFile, "w")
while 1:
    text = f.readline()
    if text == "":
        break
f2.write(text)
f.close()
f2.close()



copyFile("test.dat","cop.dat");
>>>
Traceback (most recent call last):
  File "E:/ProjectGroup/book/python/Example/CopyFile.py", line 6, in -toplevel-
    text = f.readline()
NameError: name 'f' is not defined
你的缩近没搞对。while以下的代码都没有缩近,而与def平级,这样它们不再是函数内部的代码,所以出错了。
谢谢提醒:
修改后,

#copy file
def copyFile(oldFile, newFile):
    f = open(oldFile, "r")
    f2 = open(newFile, "w")
    while 1:
        text=f.readline()
    if text == "":
        break
    f2.write(text)
    f.close()
    f2.close()



copyFile("test.dat","cop.dat")


提示:
There's and error in your program;
*** 'break' outside loop


[Copy to clipboard] [ - ]
CODE:
    while 1:
        text=f.readline()
    if text == "":
        break

缩近不对,if应与上一句相同的缩近,而你的与while的缩近一致了。改为:

[Copy to clipboard] [ - ]
CODE:
    while 1:
        text=f.readline()
        if text == "":
            break

3ks very much