问题描述:
Traceback (most recent call last): File "F:\xhktSoft\python\xhkt\考生文件夹\PY301-2.py", line 23, in <module> fo.write('{},{}\n'.format(i[0],i[1])) io.UnsupportedOperation: not writable 这是什么错误?
问题解答:
错误 io.UnsupportedOperation: not writable
通常表示你尝试对一个以不可写模式打开的文件进行写操作。这个错误的原因是你打开文件时的模式不支持写操作。
示例及解决方法
确保在打开文件进行写操作时,使用写模式 'w'
或追加模式 'a'
。以下是一个完整的示例代码,包括如何正确打开文件进行写操作和读取操作:
ls = [["张三", 12, 12, 12], ["李四", 13, 13, 13]]
# 创建并打开一个txt文件,用于写入
with open("output.txt", "w", encoding="utf-8") as fo:
for line in ls:
# 将子列表转换为字符串,每个元素用逗号隔开,然后写入文件
fo.write('{},{},{},{}\n'.format(line[0], line[1], line[2], line[3]))
# 读取文件并打印内容
with open("output.txt", "r", encoding="utf-8") as fi:
lines = fi.readlines()
for line in lines:
print(line.strip())
解释
-
写入文件:
- 使用
with open("output.txt", "w", encoding="utf-8") as fo:
打开文件,并显式指定编码为utf-8
进行写操作。 - 在
with
语句的缩进块内,对文件对象fo
进行写操作。 - 使用
fo.write(...)
方法,将每个子列表写入文件,每个元素用逗号分隔,末尾添加换行符。
- 使用
-
读取文件:
- 使用
with open("output.txt", "r", encoding="utf-8") as fi:
打开文件,并显式指定编码为utf-8
进行读取操作。 - 在
with
语句的缩进块内,对文件对象fi
进行读操作。 - 使用
fi.readlines()
方法读取文件的所有行,并打印每行内容。
- 使用
错误解决
确保你在写入文件时使用了正确的模式('w'
或 'a'
),而不是读取模式(如 'r'
)。读取模式 'r'
仅用于读取文件,不允许写入操作。