文件读取在真正的 EOF 之前得到 EOF

File read gets EOF before real EOF

我通过网络收到一个文件 (*.png),并且该文件已正确写入(以二进制模式)到 HDD。

当我尝试打开文件时,为了进一步操作,它不会加载完全损坏 png 图像的下半部分。多个 PNG 文件都会发生这种情况,因此这不是孤立的案例。

#File received a properly written to HDD
fp = open(os.path.join(self.savedir, filename), 'wb')
fp.write(part.get_payload(decode=True))
print fp.tell()             # prints correct size, in this case: 343661bytes
fp.close

# Reads the data in the file but not till the real EOF
fin = open(os.path.join(self.savedir, filename), 'rb')
data = fin.read()
print len(data)              # prints 339968
print fin.tell()             # prints correct size, in this case: 339968bytes
fin.close

我正在使用 python 2.7.9,在 linux(64 位)和 window(32 位)上,两台机器上的行为是相同的。这些代码在不同的函数中截取,现在如上所示彼此相邻以进行完整性检查。显然,该文件仅由该程序处理,并且没有任何人处理该文件的并发线程。

问题是您没有关闭文件。这一行:

fp.close

… 只是引用 close 方法作为一个值,它并没有调用它。

因此,当您以读取模式打开同一个文件时,最后一个缓冲区通常还没有刷新到磁盘。当然,当程序退出时,缓冲区通常会被刷新(虽然这不能保证......),所以当你检查文件时它看起来非常好。当您的代码尝试读取它时,它还不是很完美。

你需要括号来调用 Python 中的任何内容:

fp.close()

或者,更好的是,使用 with 语句而不是显式 close()