在Python中快速拼接文件并获得md5

2024-05-23 17:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着把一个文件分成一个+/-300千字节的小块。 对于300兆字节的文件来说,这是相当慢的(+/-1000个文件)

我还没有使用任何线程,我不确定这是否会使它运行得更快

    cs = 1
    pieces = 1000

    # Open the file
    f = open(self.file, 'rb')
    result = {}

    while cs <= pieces:

        #Filename
        filename = str(cs).zfill(5) + '.split'

        # Generate temporary filename
        tfile = filename

        # Open the temporary file
        w = open(tfile, 'wb')

        # Read the first split
        tdata = f.read(maxsize)

        # Write the data
        w.write(tdata)

        # Close the file
        w.close()

        # Get the hash of this chunk
        result[filename] = self.__md5(tfile)

        cs += 1

这是md5函数:

^{pr2}$

那么有没有什么方法可以加快速度呢?在


Tags: 文件theself字节resultopenfilenamecs
1条回答
网友
1楼 · 发布于 2024-05-23 17:18:41

读取块,将其保存到临时文件中,然后读取临时文件并计算其md5。不过,这是不必要的-您可以在块仍在内存中时计算md5。这意味着您不必打开并读取临时文件,这应该更快。在

我也推荐一个更小的块大小-也许是2^11或2^12。在

相关问题 更多 >