python - print(f.read()) io.UnsupportedOperation: 不可读
问题描述
import os
path = os.getcwd()
print(path)
filename = "aboutPython.txt"
file = path + '\\' + filename
print(file)
# open a local txt file for append
f = open(file, "a")
# read the entire file
print(f.read())
# read the first 250 characters
print(f.read(5))
# read one line
print(f.readline())
# you can append because of how the file was opened
f.write("Now the file has one more line!")
print(f.read())
此代码引发此错误:
Traceback (most recent call last):
File "C:/Users/wrk/weemos/append_file.py", line 14, in <module>
print(f.read())
io.UnsupportedOperation: not readable
解决方案
首先以读取模式打开文件r
以读取它:
f = open(file, "r")
# read the entire file
print(f.read())
# read the first 250 characters
f.seek(0)
print(f.read(5))
# read one line
f.seek(0)
print(f.readline())
f.close()
现在,再次以追加a
模式打开它以追加,然后r
再次以读取模式打开它,因为您稍后也会从中读取:
f = open(file, "a")
# you can append because of how the file was opened
f.write("Now the file has one more line!")
f.close()
f = open(file, "r")
print(f.read())
f.close()