我正在尝试将一个大文件分割成50Mb的块,并将它们保存在另一个文件中。在运行一些读/写操作之后,我的一些块小于50Mb(43Mb、17Mb等等)。虽然,我用Java编写了相同的代码,但它也有相同的问题。怎么了?我的代码如下:
顺便问一下,我们能做些什么来加快代码的分解速度?你知道吗
try:
f = open(self.__filename, 'rb')
except (OSError, IOError), e:
raise FileSplitterException, str(e)
bname = (os.path.split(self.__filename))[1]
fsize = os.path.getsize(self.__filename)
self.__chunksize = int(float(fsize)/float(self.__numchunks))
chunksz = self.__chunksize
total_bytes = 0
for x in range(self.__numchunks):
chunkfilename = bname + '-' + str(x+1) + self.__postfix
if x == self.__numchunks - 1:
chunksz = fsize - total_bytes
try:
print 'Writing file',chunkfilename
data = f.read(chunksz)
total_bytes += len(data)
chunkf = file(chunkfilename, 'wb')
chunkf.write(data)
chunkf.close()
except (OSError, IOError), e:
print e
continue
except EOFError, e:
print e
break
你的问题不清楚,因为你没有包含一个Minimal, Complete, and Verifiable example-所以我不知道你的代码到底出了什么问题。然而,在创建/模拟了我对缺失部分的猜测之后,我想我能想出一些完全符合你要求的东西。你知道吗
问题中的代码似乎专注于生成一组块,而不是50MB大小的文件。你知道吗
此代码生成50MB文件。你知道吗
在现代python中,代码的某些方面被认为是糟糕的风格——例如不使用上下文管理器来打开文件——但我没有更改这些内容,以防OP在旧的python(如2.5)上运行。你知道吗
相关问题 更多 >
编程相关推荐