为什么在我重写字符串并读取()时,它只是在python中显示“”?

2024-09-27 21:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here我创建了一个文件名rishi.txt,然后在其中添加了“HELLO WORLD”,然后读取它。 之后,我用w+模式关闭并打开它。然后我写了“BYE”,当read()文件时,它会显示一个输出:“”

 [![This is the image of my code and the output][1]][1]

Tags: 文件oftheimagetxthelloworldread
1条回答
网友
1楼 · 发布于 2024-09-27 21:26:55

发件人: https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size characters (in text mode) or size bytes (in binary mode) are read and returned. If the end of the file has been reached, f.read() will return an empty string ('').

您必须使用contextmanager并执行以下操作:

with f as open( 'rishi.txt'):
    f.read()

或致电:

asdf.seek(0)

相关问题 更多 >

    热门问题