UnsupportedOperation:不可写 python
UnsupportedOperation: not writable python
with open(r'G:\Programs\abc.txt') as f:
for line in f:
if line.startswith('logan'):
f.write('Johann Sebastian Bach')
print("Renewed line = ", line)
错误信息:
runfile('G:/Python Programs/p17.py', wdir='G:/Python Programs')
Traceback (most recent call last):
File "<ipython-input-2-393638b0e5ce>", line 1, in <module>
runfile('G:/Python Programs/p17.py', wdir='G:/Python Programs')
File "G:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
execfile(filename, namespace)
File "G:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "G:/Python Programs/p17.py", line 11, in <module>
khand.write('Johann Sebastian Bach')
UnsupportedOperation: not writable
我已经在 python3.6 中列出了这段代码,但我仍然收到一条错误消息。我在目录中有所需的文件。有什么建议么?
在没有模式的情况下打开文件默认以只读模式打开它。如果你想在阅读时写入它,你必须将模式指定为 r+
.
with open(r'G:\Programs\abc.txt', mode='r+') as khand:
...
w+
也将以 r/w 模式打开文件, 但是 ,它会将内容擦除干净。
您还可以使用 a+
模式,该模式将追加到文件末尾,同时仍让您从中读取。
with open(r'G:\Programs\abc.txt') as f:
for line in f:
if line.startswith('logan'):
f.write('Johann Sebastian Bach')
print("Renewed line = ", line)
错误信息:
runfile('G:/Python Programs/p17.py', wdir='G:/Python Programs')
Traceback (most recent call last):
File "<ipython-input-2-393638b0e5ce>", line 1, in <module>
runfile('G:/Python Programs/p17.py', wdir='G:/Python Programs')
File "G:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
execfile(filename, namespace)
File "G:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "G:/Python Programs/p17.py", line 11, in <module>
khand.write('Johann Sebastian Bach')
UnsupportedOperation: not writable
我已经在 python3.6 中列出了这段代码,但我仍然收到一条错误消息。我在目录中有所需的文件。有什么建议么?
在没有模式的情况下打开文件默认以只读模式打开它。如果你想在阅读时写入它,你必须将模式指定为 r+
.
with open(r'G:\Programs\abc.txt', mode='r+') as khand:
...
w+
也将以 r/w 模式打开文件, 但是 ,它会将内容擦除干净。
您还可以使用 a+
模式,该模式将追加到文件末尾,同时仍让您从中读取。