用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
[解决办法]
#f=file('poem.txt','w') #open for 'w'riting #应该改成f = open('poem.txt', 'w')
[解决办法]
f=file('poem.txt')#if no mode is specified,'r'ead mode is assumed by defaultwhile True: line=f.readline() if len(line)==0: #Zero length indicates EOF break print (line) #Notice comma to avoid automatic newline added by Pythonf.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多多了解一下