print(f.read()) io.UnsupportedOperation: not readable


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()

脚本失败,因为在追加模式下打开的文件没有读取权限。打开";a+";模式,如果您希望文件也是可写的。

import os
path = os.getcwd()
print(path)
filename = "aboutPython.txt"
file = os.path.join(path, filename)
print(file)
# open a local txt file for append
f = open(file, "a+")
# read the entire file
print(f.read())

现在该文件是可读的,但它位于文件的末尾,因此f.read()将返回一个空字符串。你可以

print("position at open", f.tell())
f.seek(0)
print("position after seek", f.tell())

但现在我真的只是猜测你想让这个脚本做什么

最新更新