【问题标题】:Why calling file.read in python fills my file with garbage?为什么在 python 中调用 file.read 会用垃圾填充我的文件?
【发布时间】:2014-09-18 08:15:56
【问题描述】:

运行这个:

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

【问题讨论】:

  • 为什么会有.readall() 方法?
  • 你能告诉我们你看到的“垃圾”吗?因为您的文件指针位于文件末尾,而 excl.read() 在该点返回一个空字符串。
  • @MartijnPieters:Pycharm 解决了它
  • 不知道 PyCharm 是从哪里得到的,但 Python file objects 上没有这种方法。
  • 对,PyCharm 与 Python 3 io.RawIOBase type 混淆了。

标签: python python-2.7 file-io io


【解决方案1】:

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

你也可以使用冲洗:

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

【讨论】:

  • 啊哈哈补充一下,我是一个 python 新手,你可以想象我的奇迹的深度
  • 我只是想要一个调试打印啊哈哈哈 - 不错
  • 顺便说一句,内存已初始化——当这第一次发生时,我看到我在垃圾中运行的文件 + .git/config——我以为我丢失了它:D
  • @Mr_and_Mrs_D:初始化的内存很容易包含不再使用的文件缓冲区中的数据。 :-)
猜你喜欢
  • 1970-01-01
  • 2016-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多