注册 登录
编程论坛 Python论坛

file类使用出错,怎么回事?

zjsxwc 发布于 2012-05-04 16:00, 1461 次点击
程序代码:

def TT():
    poem = '''\
    Programming is fun
    When the work is done
    if you wanna make your work also fun:
        use Python!
   
'''

    f = file('poem.txt', 'w') # open for 'w'riting
    f.write(poem) # write text to file
    f.close() # close the file

    f = file('poem.txt')
    # if no mode is specified, 'r'ead mode is assumed by default
    while True:
        line = f.readline()
        if len(line) == 0: # Zero length indicates EOF
            break
        print (line),
        # Notice comma to avoid automatic newline added by Python
    f.close() # close the file
  
出错如下:
程序代码:
>>> TT()
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    TT()
  File "<pyshell#29>", line 9, in TT
    f = file('poem.txt', 'w') # open for 'w'riting
NameError: global name 'file' is not defined


今天学了下python,定义了个TT函数,为什么一运行TT()就出现file未定义这个错误?,难道file类还要import?那么要import什么?

[ 本帖最后由 zjsxwc 于 2012-5-4 16:02 编辑 ]
2 回复
#2
hziee2012-05-11 17:04
文件对象使用,请使用open
修改:
 F= open('poem.txt', 'w') # open for 'w'riting
试试!!!
#3
快乐出发02202012-05-13 12:36
我的可以编译通过,而且能够输出结果,不过我还是建议你能够采用一楼的,把file改成open,这样更好。
1