为什么在Python中调用file.read会使我的文件充满垃圾?

1 投票
1 回答
1719 浏览
提问于 2025-04-18 14:53

运行这个代码:

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)

结果是我的文件里充满了垃圾数据 - 这是为什么呢?还有为什么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 >')

1 个回答

5

你遇到了一个在C语言层面上输入输出实现的特殊情况。当你以+模式打开文件时(在你的例子中是可以读写的),那么你必须在“切换”模式之前执行刷新或定位操作,否则行为就会变得不确定。在这种情况下,你把未初始化的内存添加到了文件中。

关于这个问题,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()

你也可以使用刷新操作:

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()

撰写回答