python - 使用python在Linux中分配特定大小的文件

标签 python linux file

我正在用 python 编写一个 I/O 密集型程序,我需要在硬盘上分配特定数量的存储空间。由于我需要尽可能快,所以我不想在循环中创建一个包含零(或虚拟)内容的文件。 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()

最佳答案

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

参见How to create a file with file holes?了解如何创建这样的文件。

关于python - 使用python在Linux中分配特定大小的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32149494/

相关文章:

javascript - 如何在 Javascript 中将文件夹中的文件名数组写入 TXT 文件

c++ - 在 std::ofstream (c++) 中复制 std::cout

c++ - 如何从 C++ 中的文件中随机获取信息?

python 使用斐波那契数列

python - 如何将数组从 C 传递到嵌入式 python 脚本

python - 一种删除列表中仅一个元素的连续重复项的pythonic方法

Linux时间转换的php函数

python - 澄清 tf.Session() 范围 TensorFlow

c - 将 pthread 变量保留在本地

linux - 未知消息 : Panel when opening gvim