Python文件读写不起作用

2024-06-18 13:27:01 发布

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

我正在为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”。在


Tags: and文件代码texttxt游戏模式open
3条回答

在a+的情况下,读和写可以同时有两个功能 为了以前的阅读文件.readlines()你应该有文件.seek(0)用于在文件开头定位文件描述符

代码:

file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
file.seek(0)
text = file.readlines()
print(text)
file.close()

它会完美工作的

这是因为文件描述符(fd)位于文件末尾, 如果需要将fd移到文件的开头

import os
file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
os.lseek(file, 0, 0)
text = file.readlines()
print(text)
['xcfghujiosdfnonoooooowhello']

看一下打开模式(python使用与Cfopen)相同的模式http://www.manpagez.com/man/3/fopen/

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate to zero length or create text file for writing.  The
         stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.

'a+'模式的描述中,可以清楚地看到流位于文件的末尾。所以在这一点上,如果你继续从当前位置(文件末尾)读取它,那么你的输出也会随之改变。在

要在这种情况下获得正确的输出,可以使用file.seek()函数,如下所示:

^{pr2}$

相关问题 更多 >