# coding= utf-8
f = open(r"e:\python27\code\data1.txt", "w") #文件路径按个人情况变更
f.write("this is a test ")
f.close()
f = open(r"e:\python27\code\data1.txt", "r")
a = f.read()
print(a)
f.close()
‘‘‘
在之前试了好多次错误的,贪图方便,打开后写完想立马读取:
# coding= utf-8
with open(r"e:\python27\code\data1.txt", "w") as f:
f.write("this is a test ")
a = f.read()
print(a)
写入正常,但读老提示错误如下:
Traceback (most recent call last):
File "E:\Python27\code\文件操作.py", line 4, in <module>
a = f.read()
IOError: File not open for reading
以为是参数“w”错了,应该改“w+”,试了,错误提示消失,但也不对,没有内容被读取到。
最终改成上在的,写完关闭文件,再重新打开读取。
想请教原因是什么?请大神指教一下!
想来应该是对机制没理解,记得说,如果打开文件没关闭,数据可能会丢失,所以一开始猜测可能是关闭时数据没存,没数据。但在存了一次之后,文件里已经有了上一次写入的信息,依然没有数据被读取,肯定是哪不对了。
’’’