Hướng dẫn how do you create a binary file in python? - làm thế nào để bạn tạo một tệp nhị phân trong python?

4

Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.
Learn more.

Tôi có một tệp nhị phân rất lớn có tên File1.Bin và tôi muốn tạo một tệp, File2.bin, chỉ chứa 32kb đầu tiên của File1.bin.

Vì vậy, tôi đang đọc File1 như sau:

myArr = bytearray[]

with open[r"C:\Users\User\file1.bin", "rb"] as f:
byte = f.read[1]
for i in range[32,678]:
    myArr.extend[byte]
    byte = f.read[1]

Câu hỏi của tôi là: Làm cách nào để tiến hành từ đây để tạo tệp nhị phân File2 ra khỏi Myarr?

Tôi đã thử

with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]

Nhưng điều này dẫn đến:

f.write[myArr]
TypeError: must be string or pinned buffer, not bytearray

Đã hỏi ngày 20 tháng 2 năm 2014 lúc 14:01Feb 20, 2014 at 14:01

SubwaysubwaySubway

4.92610 Huy hiệu vàng46 Huy hiệu bạc58 Huy hiệu Đồng10 gold badges46 silver badges58 bronze badges

8

Bạn cần mở tệp ở chế độ ghi nhị phân [wb].

with open['file2.bin', 'wb'] as f:
    f.write[myArr]

Ngoài ra, cách bạn đang đọc từ tệp đầu vào khá kém hiệu quả. f.read[] cho phép bạn đọc nhiều hơn một byte cùng một lúc:

with open['file1.bin', 'rb'] as f:
    myArr = bytearray[f.read[32678]]

Sẽ làm chính xác những gì bạn muốn.

Đã trả lời ngày 20 tháng 2 năm 2014 lúc 14:18Feb 20, 2014 at 14:18

Joel Cornettjoel CornettJoel Cornett

23,5K9 Huy hiệu vàng60 Huy hiệu bạc85 Huy hiệu Đồng9 gold badges60 silver badges85 bronze badges

Mở các tệp có cờ thích hợp, sau đó đọc từ một khối trong các khối 1024 byte và ghi sang khác, nếu còn lại dưới 1024 byte, sao chép byte-khôn ngoan.

fin = open['file1.bin', 'rb']
fout = open['file2.bin', 'w+b']
while True:
  b=fin.read[1024]
  if b:
    n = fout.write[b]
  else:
    while True:
      b=fin.read[1]
      if b:
        n=fout.write[b]
      else:
        break
    break

Đã trả lời ngày 20 tháng 2 năm 2014 lúc 14:24Feb 20, 2014 at 14:24

Các tập tin được sử dụng để lưu trữ dữ liệu vĩnh viễn. Xử lý tệp đang thực hiện các hoạt động khác nhau [đọc, viết, xóa, cập nhật, v.v.] trên các tệp này. Trong Python, quy trình xử lý tệp diễn ra trong các bước sau:

  1. Mở tệp
  2. Màn trình diễn
  3. Đóng tập tin

Có bốn chế độ cơ bản trong đó một tệp có thể được mở - đọc, ghi, nối và sáng tạo độc quyền. Ngoài ra, Python cho phép bạn chỉ định hai chế độ trong đó một tệp có thể được xử lý - nhị phân và văn bản. Chế độ nhị phân được sử dụng để xử lý tất cả các loại dữ liệu không phải là văn bản như tệp hình ảnh và tệp thực thi.

Viết các byte vào tệp trong Python

Ví dụ 1: Mở một tệp ở chế độ ghi nhị phân và sau đó chỉ định nội dung để ghi dưới dạng byte. Tiếp theo, sử dụng chức năng ghi để ghi nội dung byte vào tệp nhị phân. & Nbsp;Open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file. 

Python3

some_bytes =

with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
0
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
1

with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
2
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
3
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
4
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
5
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
6
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
7
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
8

with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
9
f.write[myArr]
TypeError: must be string or pinned buffer, not bytearray
0

Output:

my_file.txt

Ví dụ 2: Phương pháp này yêu cầu bạn tự thực hiện xử lý lỗi, nghĩa là đảm bảo rằng tệp luôn được đóng, ngay cả khi có lỗi trong khi viết. Vì vậy, bằng cách sử dụng các tuyên bố của người Viking về vấn đề này tốt hơn vì nó sẽ tự động đóng tệp khi khối kết thúc. This method requires you to perform error handling yourself, that is, ensure that the file is always closed, even if there is an error during writing. So, using the “with” statementis better in this regard as it will automatically close the file when the block ends.

Python3

some_bytes =

with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
0
f.write[myArr]
TypeError: must be string or pinned buffer, not bytearray
4

f.write[myArr]
TypeError: must be string or pinned buffer, not bytearray
5=
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
3
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
4
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
5
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
6
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
7
with open['file2.bin', 'wb'] as f:
    f.write[myArr]
2

f.write[myArr]
TypeError: must be string or pinned buffer, not bytearray
0

with open['file2.bin', 'wb'] as f:
    f.write[myArr]
4

Output:

my_file.txt

Ví dụ 3: Ngoài ra, một số_bytes có thể ở dạng bytearray có thể thay đổi hoặc đối tượng byte là bất biến như hình dưới đây.Also, some_bytes can be in the form of bytearray which is mutable, or bytes object which is immutable as shown below.

Python3

with open['file2.bin', 'wb'] as f:
    f.write[myArr]
5=
with open['file2.bin', 'wb'] as f:
    f.write[myArr]
7
with open['file2.bin', 'wb'] as f:
    f.write[myArr]
8
with open['file2.bin', 'wb'] as f:
    f.write[myArr]
9
with open['file1.bin', 'rb'] as f:
    myArr = bytearray[f.read[32678]]
0
with open['file2.bin', 'wb'] as f:
    f.write[myArr]
9
with open['file1.bin', 'rb'] as f:
    myArr = bytearray[f.read[32678]]
2
with open['file2.bin', 'wb'] as f:
    f.write[myArr]
9
with open['file1.bin', 'rb'] as f:
    myArr = bytearray[f.read[32678]]
444

some_bytes =

with open['file1.bin', 'rb'] as f:
    myArr = bytearray[f.read[32678]]
8

with open['file1.bin', 'rb'] as f:
    myArr = bytearray[f.read[32678]]
9
fin = open['file1.bin', 'rb']
fout = open['file2.bin', 'w+b']
while True:
  b=fin.read[1024]
  if b:
    n = fout.write[b]
  else:
    while True:
      b=fin.read[1]
      if b:
        n=fout.write[b]
      else:
        break
    break
0
with open['file2.bin', 'wb'] as f:
    f.write[myArr]
2

fin = open['file1.bin', 'rb']
fout = open['file2.bin', 'w+b']
while True:
  b=fin.read[1024]
  if b:
    n = fout.write[b]
  else:
    while True:
      b=fin.read[1]
      if b:
        n=fout.write[b]
      else:
        break
    break
2=
fin = open['file1.bin', 'rb']
fout = open['file2.bin', 'w+b']
while True:
  b=fin.read[1024]
  if b:
    n = fout.write[b]
  else:
    while True:
      b=fin.read[1]
      if b:
        n=fout.write[b]
      else:
        break
    break
4

with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
2
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
3
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
4
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
5
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
6
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
7
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
8

with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
9wb3

Output::

my_file.txt

Ví dụ 4: Sử dụng mô -đun byte để ghi byte vào tệp Using the BytesIO module to write bytes to File

Python3

wb4 wb5wb6 wb7

wb8= f.read[]0f.read[]1

with open['file2.bin', 'wb'] as f:
    f.write[myArr]
2

with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
2
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
3
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
4f.read[]6
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
6
with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
7f.read[]9

with open[r"C:\Users\User\file2.bin", "w"] as f:
f.write[myArr]
9some_bytes 1

Output:

test.bin


Làm cách nào để tạo một tệp nhị phân trong Python?

Viết byte vào tệp trong Python Ví dụ 1: Mở tệp ở chế độ ghi nhị phân và sau đó chỉ định nội dung để ghi dưới dạng byte. Tiếp theo, sử dụng chức năng ghi để viết nội dung byte vào tệp nhị phân.use the write function to write the byte contents to a binary file.

Làm thế nào để bạn tạo một tệp nhị phân?

Cách tạo tệp nhị phân..
Thêm không gian tên vào trang mã của dự án của bạn. Viết và đọc các tệp yêu cầu không gian tên "IO". ....
Tạo biến FileStream và gán nó cho một luồng nhị phân. ....
Viết vào tệp nhị phân bằng hàm "Viết". ....
Đóng tệp sau khi tất cả thông tin đã được lưu vào tệp ..

Định dạng tệp nhị phân trong Python là gì?

Một tệp nhị phân là một tệp có nội dung ở định dạng nhị phân bao gồm một loạt các byte tuần tự, mỗi loại có chiều dài tám bit.Nội dung phải được giải thích bởi một chương trình hoặc bộ xử lý phần cứng hiểu trước chính xác cách nội dung đó được định dạng và cách đọc dữ liệu.a file whose content is in a binary format consisting of a series of sequential bytes, each of which is eight bits in length. The content must be interpreted by a program or a hardware processor that understands in advance exactly how that content is formatted and how to read the data.

Làm cách nào để chuyển đổi chuỗi thành tệp nhị phân trong Python?

Thí dụ -..
# khai báo chuỗi ..
str_to_conv = "Hãy tìm hiểu Python".
# in chuỗi sẽ được chuyển đổi ..
in ["Chuỗi mà chúng tôi đã thực hiện là", str_to_conv].
# Sử dụng tham gia [] + ord [] + định dạng [] để chuyển đổi thành nhị phân ..
bin_result = '' .join [định dạng [ord [x], '08b'] cho x trong str_to_conv].
# in kết quả ..

Bài Viết Liên Quan

Chủ Đề