Hướng dẫn python bytesio context manager - trình quản lý bối cảnh bytesio python

Tôi đang cố gắng sử dụng Trình quản lý ngữ cảnh cho luồng byteo trong khi tạo nhiều tệp zip. Tôi không thể tìm thấy cách nào để "đặt lại" đối tượng byte sau khi tệp zip đầu tiên được viết, vì vậy tôi có thể sử dụng cùng một đối tượng byte để tạo tệp zip tiếp theo. Tôi luôn nhận được lỗi "Không thể mở tệp ... dưới dạng lưu trữ" khi cố gắng mở tệp zip thứ hai sau khi được ghi vào đĩa. Tệp zip đầu tiên mở tốt. Tôi đã tìm kiếm và không thể tìm thấy một giải pháp. Thay đổi chế độ từ ghi sang phần phụ cũng không giúp được gì. Tất nhiên, tôi có thể tái tạo thành một đối tượng byte mới, nhưng điều đó đánh bại người quản lý bối cảnh. Dưới đây là mã tôi nghĩ nên hoạt động. Tôi đang sử dụng Anaconda Python 3.6.6 trên Windows 10.

import io
import os
import zipfile

with io.BytesIO() as bytes_io:
    with zipfile.ZipFile(bytes_io, mode='w') as zf:
        filecount = 0
        for item in os.scandir(r'C:\Users\stephen\Documents'):
            if not item.is_dir():
                zf.write(item.path, item.name)
                filecount += 1
                if filecount % 3 == 0:
                    with open(r'C:\Users\stephen\Documents\\' + str(filecount // 3) + '.zip', 'wb') as f:
                        f.write(bytes_io.getvalue())
                    bytes_io.seek(0)
                    bytes_io.truncate()

Hỏi ngày 5 tháng 10 năm 2018 lúc 5:13Oct 5, 2018 at 5:13

Hướng dẫn python bytesio context manager - trình quản lý bối cảnh bytesio python

0

Bạn có thể sử dụng lại cùng một đối tượng BytesIO, nhưng bạn nên tạo một đối tượng ZipFile mới cho mọi tệp zip bạn muốn tạo:

with io.BytesIO() as bytes_io:
    filecount = 0
    for item in os.scandir(r'C:\Users\stephen\Documents'):
        if not item.is_dir():
            with zipfile.ZipFile(bytes_io, mode='w') as zf:
                zf.write(item.path, item.name)
            filecount += 1
            if filecount % 3 == 0:
                with open(r'C:\Users\stephen\Documents\\' + str(filecount // 3) + '.zip', 'wb') as f:
                    f.write(bytes_io.getvalue())
                bytes_io.seek(0)
                bytes_io.truncate()

Đã trả lời ngày 5 tháng 10 năm 2018 lúc 5:49Oct 5, 2018 at 5:49

blhsingblhsingblhsing

83K6 Huy hiệu vàng65 Huy hiệu bạc95 Huy hiệu Đồng6 gold badges65 silver badges95 bronze badges

4

2021-04-13 & NBSP; 20: 02: 34

tạo ra2021-04-13 20:02 by John Hagen, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Số phát hành43834
Được tạo ra vào ngày 2021-04-13 20:02 của John Hagen, lần cuối đã thay đổi 2022-04-11 14:59 bởi quản trị viên. Vấn đề giờ đã kết thúc.Kéo yêu cầuURLTrạng thái
Liên kếtChỉnh sửa PR 25401, 2021-04-14 12:11
Đóng
John Hagen, 2021-04-14 12:11Tin nhắn (4)* MSG391000 - (Xem)
Tác giả: John Hagen (John Hagen) *
Ngày: 2021-04-13 20:02
The example for StringIO currently manually closes the object rather than using a context manager. Since this is likely the first code that a new user encounters and context managers reduce error-prone situations, I think it would be helpful to show usage as a context manager.

https://docs.python.org/3/library/io.html#io.StringIO.getvalue

Something like:

import io

with io.StringIO() as output:
    output.write('First line.\n')
    print('Second line.', file=output)

    # Retrieve file contents -- this will be
    # 'First line.\nSecond line.\n'
    contents = output.getvalue()

# Context manager will automatically close
# object and discard memory buffer --
# .getvalue() will now raise an exception.
*
Hướng dẫn python bytesio context manager - trình quản lý bối cảnh bytesio python
MSG391415 - (Xem)
Tác giả: Raymond Hettinger (Rhettinger) *
Ngày: 2021-04-19 23:25
The example for StringIO currently manually closes the object rather than using a context manager. Since this is likely the first code that a new user encounters and context managers reduce error-prone situations, I think it would be helpful to show usage as a context manager.

https://docs.python.org/3/library/io.html#io.StringIO.getvalue

Something like:

import io

with io.StringIO() as output:
    output.write('First line.\n')
    print('Second line.', file=output)

    # Retrieve file contents -- this will be
    # 'First line.\nSecond line.\n'
    contents = output.getvalue()

# Context manager will automatically close
# object and discard memory buffer --
# .getvalue() will now raise an exception.
*
Hướng dẫn python bytesio context manager - trình quản lý bối cảnh bytesio python
MSG391415 - (Xem)
Tác giả: Raymond Hettinger (Rhettinger) *
Ngày: 2021-04-19 23:25
Let's leave the example as-is.   The principal use case for these objects is to pass them into other APIs that require file-like objects.  Those can't always be put in a context manager.  For this example, we mainly want to communicate that getvalue() must be called before the object is closed.  The current form communicates that clearly.

Thanks for the suggestion.
*
Hướng dẫn python bytesio context manager - trình quản lý bối cảnh bytesio python
MSG391416 - (Xem)
Ngày: 2021-04-19 23:27
Except for that, the PR looks fine.  Leaving this open to see what Benjamin thinks.
MSG391417 - (Xem)Tác giả: Benjamin Peterson (Benjamin.peterson) *Ngày: 2021-04-20 00:32
I agree that closing or using a context manager with StringIO (or BytesIO) is not something one normally has to do, so it doesn't need to be in the example.
Lịch sửNgàybộNgười sử dụng
Hoạt độngArgsbộ2022-04-11 & NBSP; 14: 59: 44
resolution: rejected
messages: + msg391417
quản trị viênGitHub: 88000bộ2021-04-20 & NBSP; 00: 32: 20
resolution: rejected -> (no value)
messages: + msg391416
Benjamin.petersonGitHub: 88000bộ2021-04-20 & NBSP; 00: 32: 20

Benjamin.peterson
messages: + msg391415

Trạng thái: Mở -> ĐóngResolution: DespckedMessages: + MSG391417
stage: patch review -> resolved

2021-04-19 & NBSP; 23: 27: 32Terry.reedybộNosy: + Benjamin.peterson, Stutzbach
2021-04-14 & NBSP; 12: 11: 28John HagenbộNosy: + Benjamin.peterson, Stutzbach
stage: patch review
pull_requests: + pull_request24133
2021-04-14 & NBSP; 12: 11: 28John HagenTừ khóa: + PatchStage: Patch ReviewPull_Requests: + pull_request24133