I am writing an I/O intensive program in python and I need to allocate a specific amount of storage on hard disk. Since I need to be as fast as possible I do not want to make a file with zero (or dummy) content in a loop. Does python have any library or method to do so, or do I have to use a Linux command in python?
Actually, I am implementing an application that works like BitTorrent. In my code, the receiver stores every segment of the source file in a separate file (each segment of the source file comes from a random sender). At the end, all the separate files will be merged. It takes lots of time to do so.
Therefore, I want to allocate a file in advance and then write every received segment of the source file in its offset in the pre-allocated file.
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()