我正在为Python做一个游戏,里面有一些代码可以把答案写到一个文件中,当我自己运行它的时候,为了防止自己不得不真正玩这个游戏。
我已经为编写和读取一个运行良好的文件编写了代码,但是对于cheat.txt文件,打印其内容只返回[]
。在
下面是一个简短的例子。在
file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
text = file.readlines()
print(text)
[]
file.close()
file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "r+")
text = file.readlines()
print(text)
['xcfghujiosdfnonoooooowhello']
现在在网络机器上,a+不工作,而r+工作。我完全理解每个模式的功能,但是有人能告诉我为什么在+模式下它不能读(或写,返回参数的长度)?在
注意+是必需的模式,因为它需要附加到文件中。在
编辑:当我输入file.write()
时,帮助您应用参数的小框显示为“See source or doc”。在
在a+的情况下,读和写可以同时有两个功能 为了以前的阅读文件.readlines()你应该有文件.seek(0)用于在文件开头定位文件描述符
代码:
它会完美工作的
这是因为文件描述符(fd)位于文件末尾, 如果需要将fd移到文件的开头
看一下打开模式(python使用与C
fopen
)相同的模式http://www.manpagez.com/man/3/fopen/在
'a+'
模式的描述中,可以清楚地看到流位于文件的末尾。所以在这一点上,如果你继续从当前位置(文件末尾)读取它,那么你的输出也会随之改变。在要在这种情况下获得正确的输出,可以使用
^{pr2}$file.seek()
函数,如下所示:相关问题 更多 >
编程相关推荐