Python文件读写不工作

ois*_*nvg 1 python file

我正在为 Python 制作一个游戏,其中有代码可以将我自己运行时的答案写入文件,以防止自己不得不实际玩游戏。我已经编写了用于编写和读取一个工作正常的文件的编码,但是对于作弊 .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']
Run Code Online (Sandbox Code Playgroud)

现在在网络机器上出现 a+ 不起作用,而是 r+。我完全理解每种模式的功能,但是谁能提出为什么它在 a+ 模式下无法读取(或写入,返回参数的长度)?

注意 a+ 是必需的模式,因为它需要附加到文件中。

编辑:当我输入时file.write(),帮助您应用参数的小框显示为“查看源代码或文档”。

Tom*_*ota 6

看看打开模式(python 使用与 C 相同的模式fopenhttp://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.
Run Code Online (Sandbox Code Playgroud)

您可以在'a+'模式描述中清楚地看到流位于文件末尾。因此,此时如果您执行读取,将从当前位置(文件末尾)继续读取,从而输出。

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

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

['actual output']
Run Code Online (Sandbox Code Playgroud)