Python文件读写不起作用

时间:2017-03-30 09:10:11

标签: 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']

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

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

编辑:当我输入file.write()时,帮助您应用参数的小方框会显示'请参阅来源或文档'。

3 个答案:

答案 0 :(得分:2)

看看开放模式(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']

答案 1 :(得分:1)

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

答案 2 :(得分:1)

如果读取和写入都是+,则可以使用两个函数 在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()

它将完美地运作