我正在编写一个I / O密集型程序在Python中,我需要分配一个特定数量的硬盘上的存储空间。 由于我需要尽可能快,我不想在循环中创build零(或虚拟)内容的文件。 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驱动程序在预先创建一个明显为零的文件时支持稀疏文件,然后执行寻道和写入循环到需要编写特定位数据。
请参阅如何使用文件洞创建文件? 了解如何创建这样的文件。