专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Perl/Python

用file的write()方法无法写文件怎么处理

发布时间:2011-06-29 20:10:31 文章来源:www.iduyao.cn 采编人员:星星草
用file的write()方法无法写文件怎么办?
有这样一个程序:
# !/usr/bin/python
# Filename:using_file.py

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

______________________________________
运行后出现如下错误提示:
>>> 
Traceback (most recent call last):
  File "D:/Python30/using_file.py", line 6, in <module>
  f=file('poem.txt','w') #open for 'w'riting
NameError: name 'file' is not defined
是怎么回事?
我用的Python开发环境是Python 3.1

------解决方案--------------------
Python code

#f=file('poem.txt','w') #open for 'w'riting 
#应该改成
f = open('poem.txt', 'w')

------解决方案--------------------
Python code

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 

#更通用的写法是这样子的:
f = open('poem.txt')
lines = f.readlines() #读取所有的行
f.close()

for line in lines:
    print(line)

------解决方案--------------------
lz代码是Python2的,Python3中用open
------解决方案--------------------
lz多次问的问题都是在Python3上使用Python2的代码导致的
Python3与Python2不兼容,有很多改进,建议lz多多了解一下
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: