Python 分割文件

2024-06-01 07:19:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有一个脚本,它通过请求.post(). 服务器在同一个流中向我发送两个文件。我现在处理这个问题的方法是将其全部保存为一个文件,再次打开它,根据正则表达式字符串拆分文件,将其另存为新文件,然后删除旧文件。文件足够大,我必须在我的请求.post()语句并分块写。在

我希望也许有人知道一个更好的方法来发布帖子或处理返回的数据,以便第一次正确地存储文件?或者这是最好的方法吗?在

----添加当前代码----

if not os.path.exists(output_path):
    os.makedirs(output_path)

memFile = requests.post(url, data=etree.tostring(etXML), headers=headers, stream=True)

outFile = open('output/tempfile', 'wb')

for chunk in memFile.iter_content(chunk_size=512):
    if chunk:
        outFile.write(chunk)

f = open('output/tempfile', 'rb').read().split('\r\n\r\n')

arf = open('output/recording.arf', 'wb')
arf.write(f[3])
os.remove('output/tempfile')

Tags: 文件path方法outputifosopentempfile
1条回答
网友
1楼 · 发布于 2024-06-01 07:19:20

好吧,我很无聊,想找出最好的办法。原来,我在上面的评论中最初的方式过于复杂(除非考虑到时间非常关键,或者内存受到严重限制的情况)。缓冲区是实现这一点的一种简单得多的方法,只要一次使用两个或多个块。此代码模拟用于演示的问题场景。在

注意:根据regex引擎的实现,这会更高效,并且需要的str/byte转换要少得多,因为使用regex需要将每个字节块强制转换为字符串。下面的方法不需要字符串转换,而是只对request.post()返回的字节进行操作,然后将这些相同的字节写入文件,而不进行转换。在

from pprint import pprint

someString = '''I currently have a script that requests a file via a requests.post(). The server sends me two files in the same stream. The way I am processing this right now is to save it all as one file, open it again, split the file based on a regex string, save it as a new file, and delete the old one. The file is large enough that I have to stream=True in my requests.post() statement and write it in chunks.

I was hoping that maybe someone knows a better way to issue the post or work with the data coming back so that the files are stored correctly the first time? Or is this the best way to do it?'''

n = 16
# emulate a stream by creating 37 blocks of 16 bytes
byteBlocks = [bytearray(someString[i:i+n]) for i in range(0, len(someString), n)]
pprint(byteBlocks)

# this string is present twice, but both times it is split across two bytearrays
matchBytes = bytearray('requests.post()')

# our buffer
buff = bytearray()

count = 0
for bb in byteBlocks:
    buff += bb
    count += 1

    # every two blocks
    if (count % 2) == 0:

        if count == 2:
            start = 0
        else:
            start = len(matchBytes)

        # check the bytes starting from block (n -2 -len(matchBytes)) to (len(buff) -len(matchBytes))
        # this will check all the bytes only once...
        if matchBytes in buff[ ((count-2)*n)-start : len(buff)-len(matchBytes) ]:
            print('Match starting at index:', buff.index(matchBytes), 'ending at:', buff.index(matchBytes)+len(matchBytes))

更新:

因此,考虑到更新后的问题,此代码可能不需要创建临时文件。我还不能准确地测试它,因为我没有类似的响应,但是您应该能够自己找出任何bug。在

因为您实际上并不直接使用流,也就是说,您从请求.post(),那么您就不必担心使用网络意义上的块。请求所指的“块”实际上是它发出字节的方式,它已经拥有了所有字节。您可以使用r.raw.read(n)直接访问字节,但据我所知,request对象不允许您查看“r.raw”中有多少字节,因此您或多或少被迫使用“iter_content”方法。在

无论如何,这段代码应该将请求对象中的所有字节复制到一个字符串中,然后您可以像以前一样搜索和分割该字符串。在

^{pr2}$

相关问题 更多 >