Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python r+;读写读写将垃圾写入文件_Python_Garbage - Fatal编程技术网

python r+;读写读写将垃圾写入文件

python r+;读写读写将垃圾写入文件,python,garbage,Python,Garbage,有人能解释一下为什么会出现以下问题吗。 在Python2.7.12中,当读取、写入并随后再次读取文件时,Python似乎在写垃圾 例如,在python IDLE中运行时: import os testPath = r"myTestFile.txt" ## Make sure the file exists and its empty with open(testPath,"w") as tFile: tFile.write("") print "Our Test File: ",

有人能解释一下为什么会出现以下问题吗。 在Python2.7.12中,当读取、写入并随后再次读取文件时,Python似乎在写垃圾

例如,在python IDLE中运行时:

import os 
testPath = r"myTestFile.txt"

## Make sure the file exists and its empty
with open(testPath,"w") as tFile:
    tFile.write("")

print "Our Test File: ", os.path.abspath(testPath )

with open(testPath, "r+") as tFile:
    ## First we read the file 
    data = tFile.read()

    ## Now we write some data 
    tFile.write('Some Data')

    ## Now we read the file again
    tFile.read()
现在查看文件时,数据如下所示:

一些数据@sbd Z d d l m Z d d d・ ・ YZ e d k r^d l m Z e d d d d・n d S(s9
利用历史实现空闲Shell历史机制

在我看来,read函数从文件的末尾开始读取,然后读入后面的任何对象的内存,但这只是纯粹的推测

我查找了似乎打印到文本文件中的文本,这些数据来自:

Python27\Lib\idlelib\IdleHistory.py
现在我知道我应该在write函数之后使用
seek(0)
来解决这个问题。但是我对为什么会出现这个问题感兴趣

为什么最后一个read()调用似乎要将数据写入文件

谢谢

  • 注意:我在Python2.7.12和Python3.5.2中测试了它 在Python3.5.2中,它似乎是固定的,并且不写入任何垃圾数据

在某些操作系统(Windows)上,在没有
seek
的情况下读写是无效的。从内存的另一部分写入数据似乎有点粗略,但如果在C库级别调用未定义的行为,几乎任何事情都可能发生。至少不会。我无法在OS X上的Python 2.7或3.5上重现该问题。很可能是Windows指定的ic.如果文件以二进制文件打开会发生什么?在Windows 7上用Python 2.7肯定确认了这一点。事实上,在一整页胡说八道之前,我已经在文件中写入了大量Python代码。这让我感到惊讶的是,我以前没有注意到,我搜索过,也找不到它。我一直在查看2.7源代码和只能看到有关行结尾的问题(因此建议使用“b”)。这看起来像是缓冲区溢出。我将查找Python 3源代码中的差异。下面是Jan打开的示例。