为什么 read() 在 open() 函数 python 中不能与"w+"或"r+"模式一起使用



当我使用带有"r+"或"w+"参数的open时,它不想读取文本文件。

内部文本文档:

hello

Python代码示例:

代码:

with open(file_name, 'r') as o:
print(o.read())

输出:

hello

代码:

with open(file_name, 'r+') as o:
print(o.read())

输出:


代码:

with open(file_name, 'w+') as o:
o.write('hello')
print(o.read())

输出:


我还尝试将o.read()设置为变量,然后打印它,但仍然没有输出。如果有人能告诉我为什么会发生这种事,那就太好了。

with open(file_name, 'r') as o:
print(o.read())

输出你好,正如您所说。

with open(file_name, 'r+') as o:
print(o.read())

输出hello。我不知道你为什么说它什么都不输出。

with open(file_name, 'w+') as o:
o.write('hello')
print(o.read())

不输出任何内容,因为"w+"抛出文件的当前内容,然后在将hello写入文件后,文件指针位于文件的末尾,读取尝试从该点读取。要阅读您所写的内容,您需要首先查找文件的开头:

with open(file_name, 'w+') as o:
o.write('hello')
o.seek(0)
print(o.read())

打印:

hello

请参阅https://docs.python.org/3/library/functions.html#open了解更多详细信息。

with open(file_name, 'r') as o:
print(o.read())

输出hello,因为打开文件以读取

with open(file_name, 'r+') as o:
print(o.read())

还输出hello,因为文件仍处于打开状态以读取

with open(file_name, 'w+') as o:
print(o.read())

由于文件被截断,因此不输出任何内容。

请参阅https://docs.python.org/3/library/functions.html#open了解更多详细信息。

最新更新