【问题标题】:Allocate a file of particular size in Linux with python使用python在Linux中分配特定大小的文件
【发布时间】:2015-11-15 22:33:47
【问题描述】:

我正在用 python 编写一个 I/O 密集型程序,我需要在硬盘上分配特定数量的存储空间。因为我需要尽可能快,所以我不想在 loop 中创建一个内容为零(或虚拟)的文件。 python是否有任何库或方法可以这样做,还是我必须在python中使用Linux命令?

实际上,我正在实现一个类似于 BitTorrent 的应用程序。在我的代码中,接收方将源文件的每一段存储在一个单独的文件中(源文件的每一段都来自一个随机的发送方)。最后,所有单独的文件将被合并。这样做需要很多时间。

因此,我想提前分配一个文件,然后将源文件的每个接收到的段写入预分配文件中的偏移量。

def handler(self):    
    BUFFER_SIZE = 1024  # Normally 1024, but we want fast response
    # self.request is the TCP socket connected to the client
    data = self.request.recv(BUFFER_SIZE)
    addr = ..... #Some address

    details = str(data).split() 
    currentFileNum = int(details[0]) #Specifies the segment number of the received file.
    totalFileNumber = int(details[1].rstrip('\0')) # Specifies the total number of the segments that should be received.
    print '\tReceive: Connection address:', addr,'Current segment Number: ', currentFileNum, 'Total Number of file segments: ', totalFileNumber

    f = open(ServerThreadHandler.fileOutputPrefix + '_Received.%s' % currentFileNum, 'wb')
    data = self.request.recv(BUFFER_SIZE)
    while (data and data != 'EOF'):
        f.write(data)
        data = self.request.recv(BUFFER_SIZE)
    f.close()
    print "Done Receiving." ," File Number: ", currentFileNum
    self.request.sendall('\tThank you for data. File Number: ' + str(currentFileNum))
    ServerThreadHandler.counterLock.acquire()
    ServerThreadHandler.receivedFileCounter += 1
    if ServerThreadHandler.receivedFileCounter == totalFileNumber:
        infiles = []
        for i in range(0, totalFileNumber):
            infiles.append(ServerThreadHandler.fileOutputPrefix + '_Received.%s' % i)

        File_manipulation.cat_files(infiles, ServerThreadHandler.fileOutputPrefix + ServerThreadHandler.fileOutputSuffix, BUFFER_SIZE) # It concatenates the files based on their segment numbers. 
    ServerThreadHandler.counterLock.release()

【问题讨论】:

  • 你的问题不清楚,可以加点代码说清楚!
  • 你的问题是重复的:stackoverflow.com/questions/8816059/…
  • @imanMirzadeh 我已阅读该帖子,但该解决方案可能会产生您可能无法预料的结果。另一个使用“截断”方法的解决方案是用于 NTFS 文件系统。
  • 可能是this answerthis answer
  • 我编辑了问题并解释了细节。代码很简单。它打开很多文件,写入它们,最后根据它们的段号合并所有文件。它可以工作,但速度很慢。 @Kasramvd

标签: python linux file


【解决方案1】:

通常(不仅在 Python 中,而且在操作系统级别)现代 FS 驱动程序支持sparse files,当您预先创建一个明显为零填充的文件,然后执行查找和写入循环到您需要写入的点时特定的数据位。

请参阅How to create a file with file holes? 了解如何创建此类文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2019-07-30
    相关资源
    最近更新 更多