为什么在python中调用file.read会用垃圾填充我的文件?

Mr_*_*s_D 1 python io file-io python-2.7

运行这个:

import os

if __name__ == '__main__':
    exclude = os.path.join(
        r"C:\Dropbox\eclipse_workspaces\python\sync\.git", "info", "exclude")
    with open(exclude, 'w+') as excl:  # 'w' will truncate
        # print excl.read() # empty
        # excl.readall() # AttributeError: 'file' object has no attribute
        # 'readall' -- this also I do not understand
        excl.write('This will be written as expected if I comment the
         line below')
        print "Garbage\n\n", excl.read()
    # if I do not comment the line however, the file contains all the garbage
    # excl.read() just printed (edit: in addition to the line I wrote)
Run Code Online (Sandbox Code Playgroud)

导致用垃圾填充我的文件 - 为什么?还为什么readall没有解决?

Python 2.7.3

最新迭代:

#!/usr/bin/env python2
import os

if __name__ == '__main__':
    exclude = os.path.join(r"C:\Users\MrD","exclude")
    with open(exclude,'w+') as excl:
        excl.write('This will be written if I comment the line below')
        print "Garbage\n\n",excl.read()
    # now the file contains all the garbage
    raw_input('Lol >')
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

在C级实现I/O的方式已经达到了一种特殊性.当您以+模式打开文件(在您的情况下写入和读取)时,您必须在"切换"模式之前发出刷新或搜索,否则行为是未定义的.在这种情况下,您将未初始化的内存添加到文件中.

Python问题跟踪器中有一个报告:http://bugs.python.org/issue1394612

如果你想回读你所写的内容,解决方法就是重新开始:

with open(exclude,'w+') as excl:
    excl.write('This will be written if I comment the line below')
    excl.seek(0)
    print "No more garbage\n\n", excl.read()
Run Code Online (Sandbox Code Playgroud)

你也可以使用同花顺:

with open(exclude,'w+') as excl:
    excl.write('This will be written if I comment the line below')
    excl.flush()
    print "No more garbage, eof so empty:\n\n", excl.read()
Run Code Online (Sandbox Code Playgroud)