파일을 지정된 너비의 세그먼트로 나누는 소비자 프로그램이 세그먼트를 가져 와서 원본 파일의 복사본을 만듭니다. 세그먼트가 잘못되어 있으므로 오프셋 값을 사용하여 파일에 쓰려고합니다. 받는 쪽의 모든 데이터를 보유 할 로컬 배열을 만들지 않고이 방법을 사용할 수 있습니까? 예를 들어오프셋을 기반으로 파일에 파이썬 쓰기
,
f = open(file, "wb")
f.seek(offset)
f.write(data)
이 뒤에 아이디어는 파일을 전송하는 프로그램이 파일을 전송 완료하지 못할 수도 있습니다, 그리고 그것을 시작되면 다시 재개 할 것입니다. 버퍼 위치에 데이터를 배치하려고 할 때 "combine_bytes"함수가 예외를 throw하는 샘플 코드가 있습니다.
import sys
import os
def SplitFile(fname, start, end, width):
t_fileSize = os.path.getsize(fname)
buffData = bytearray(t_fileSize)
for line, offset in get_bytes(fname, int(start), int(end), int(width)):
combine_bytes(buffData, offset, line, width)
nums = ["%02x" % ord(c) for c in line]
print " ".join(nums)
f = open("Green_copy.jpg", "wb")
f.write(buffData)
f.close()
def combine_bytes(in_buff, in_offset, in_data, in_width):
#something like memcpy would be nice
#in_buff[in_offset:in_offset + in_width] = in_data
#this works but it's the mother of inefficiency
i = in_offset
for c in in_data:
in_buff.insert(i, c)
i = i + 1
def get_bytes(fname, start, end, width):
t_currOffset = start
t_width = width
f = open(fname, "r+b")
if end != 0:
while t_currOffset < end:
f.seek(t_currOffset)
if (t_currOffset + t_width) > end:
t_width = end - t_currOffset
t_data = f.read(t_width)
yield t_data,t_currOffset
t_currOffset += t_width
else:
f.seek(t_currOffset)
t_data = f.read(t_width)
while t_data:
yield t_data, t_currOffset
t_currOffset += t_width
f.seek(t_currOffset)
t_data = f.read(t_width)
f.close()
if __name__ == '__main__':
try:
SplitFile(*sys.argv[1:5])
except:
print "Unexpected error:", sys.exc_info()[0]
자세한 정보가 필요하시면 알려주세요. 코드에 이해하기 쉽거나 테스트하기 어려운 몇 개의 들여 쓰기 오류가 있습니다. (첫 번째'for '안에있는 combine_bytes 호출과 같이 - 다른 레벨에 들여 쓰기해야합니다.) – jsbueno