繁体   English   中英

Python文件读写不起作用

[英]Python file reading and writing is not working

我正在为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']

现在似乎在网络计算机上,a +不起作用,但是r +。 我完全理解每种模式的功能,但是有人可以建议为什么在a +模式下它无法读取(或写入,它返回参数的长度)吗?

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

编辑:当我键入file.write() ,协助您应用参数的小框显示为“请参阅源代码或文档”。

看一下打开模式(python使用与C fopen相同的模式) 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()函数:

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

['actual output']

发生这种情况是因为文件描述符(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']

如果同时使用a +进行读取和写入,则可以在file.readlines()之前分别使用两个函数进行读取,您应该具有file.seek(0)以便在文件开始处定位文件描述符

代码:

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

它将完美地工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM