| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1461 人关注过本帖
标题:file类使用出错,怎么回事?
只看楼主 加入收藏
zjsxwc
Rank: 7Rank: 7Rank: 7
等 级:黑侠
威 望:1
帖 子:252
专家分:601
注 册:2011-1-20
结帖率:93.75%
收藏
已结贴  问题点数:10 回复次数:2 
file类使用出错,怎么回事?
程序代码:
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 编辑 ]
搜索更多相关主题的帖子: color file 
2012-05-04 16:00
hziee
Rank: 4
等 级:业余侠客
帖 子:64
专家分:257
注 册:2010-3-12
收藏
得分:10 
文件对象使用,请使用open
修改:
 F= open('poem.txt', 'w') # open for 'w'riting
试试!!!
2012-05-11 17:04
快乐出发0220
Rank: 3Rank: 3
等 级:论坛游侠
威 望:1
帖 子:45
专家分:130
注 册:2012-4-13
收藏
得分:0 
我的可以编译通过,而且能够输出结果,不过我还是建议你能够采用一楼的,把file改成open,这样更好。
2012-05-13 12:36
快速回复:file类使用出错,怎么回事?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015304 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved