我通过网络接收一个文件(*.png),该文件被正确地写入(二进制模式)到硬盘。
当我试图打开该文件时,为了进一步的操作,它不会完全加载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位)和窗口(32位)上--这两台机器上的行为都是一样的。这些代码片段在不同的函数中,现在如上面所示,用于检查是否正常。显然,该文件仅由该程序处理,并且没有任何处理该文件的线程。
发布于 2015-04-30 07:48:57
问题是你没有关闭文件。这一行:
fp.close…只要将close方法引用为值,它就不会调用它。
因此,当您在读取模式下打开同一个文件时,最后一个缓冲区通常还没有刷新到磁盘。当然,当程序退出时,缓冲区通常会被刷新(尽管这并不保证是…)。所以当你去检查文件的时候,它看起来很好。只是当您的代码试图阅读它时,它还不是很好。
您需要括号来调用Python中的任何内容:
fp.close()或者,更好的方法是使用with语句而不是显式close()。
https://stackoverflow.com/questions/29961873
复制相似问题