读取所有行时出错io.UnsupportedOperation: not readable
f=open("/Users/jing/Desktop/test.txt","w")
content = f.write("hello\nworld\n133")
aa = f.readlines()
print(aa)
错误提示
w只写不能读取
解决方法:
1、open中的读取方法改成w+
2、使用两次f.close关闭文件
示例:
1、
f=open("/Users/jing/Desktop/test.txt","w+")
content = f.write("hello\nworld\n133")
aa = f.readlines()
print(aa)
结果
此处显示的是空列表,原因是使用w+时,文件时新建在写入,光标在文件的末尾,所以读取的时候是空的,需要将光标移至开头,代码如下
f=open("/Users/jing/Desktop/test.txt","w+")
content = f.write("hello\nworld\n133")
f.seek(0)
aa = f.readlines()
print(aa)
f.close()
结果如下:
2、
f=open("/Users/jing/Desktop/test.txt","w")
content = f.write("hello\nworld\n133")
f.close()
f=open("/Users/jing/Desktop/test.txt","r")
aa = f.readlines()
print(aa)
f.close()
结果如下: