杰瑞科技汇

Python如何写入二进制文件?

Of course! Writing binary data in Python is a common task, especially for creating files like images, executables, or serialized data. The key is to use Python's built-in open() function in binary write mode.

Python如何写入二进制文件?-图1
(图片来源网络,侵删)

The most important thing to remember is that when you write in binary mode, you must pass bytes objects to the write methods, not strings.


The Core Concept: open() in Binary Mode

You open a file for binary writing by adding the 'b' character to the mode string.

  • 'wb': Write Binary. This is the most common mode. It creates the file if it doesn't exist or overwrites it if it does. The file pointer starts at the beginning.
  • 'ab': Append Binary. This mode creates the file if it doesn't exist. If it does exist, the file pointer is placed at the end of the file, so all new data is appended.
# Syntax for opening a file in binary write mode
file_object = open('filename.bin', 'wb') 
# ... do writing ...
file_object.close()

Crucial Point: You cannot write strings like "hello" directly. You must encode them into bytes first, usually using the .encode() method.


Example 1: Writing a Simple String to a Binary File

Let's write the text "Hello, Binary World!" to a file named hello.bin.

Python如何写入二进制文件?-图2
(图片来源网络,侵删)
# The string we want to write
text_to_write = "Hello, Binary World!"
# 1. Open the file in binary write mode ('wb')
# The 'with' statement is best practice as it automatically closes the file
with open('hello.bin', 'wb') as f:
    # 2. Encode the string into bytes and write it
    # The default encoding is 'utf-8', which is a good choice.
    f.write(text_to_write.encode('utf-8'))
print("File 'hello.bin' created successfully.")

Verification: If you were to open hello.bin in a text editor, you'd likely see garbled characters because it's not a plain text file. To verify the content, you can read it back in Python:

# Reading the file back in binary mode to confirm
with open('hello.bin', 'rb') as f:
    # Read the content and decode it back to a string
    content = f.read().decode('utf-8')
print(f"Content read from file: {content}")
# Expected output: Content read from file: Hello, Binary World!

Example 2: Writing Numeric Data (Integers, Floats)

You often want to write numbers to a file. You can convert them to their byte representation using the int.to_bytes() and float.to_bytes() methods.

Let's write an integer 255 and a floating-point number 14 to a file named numbers.bin.

import struct # A more robust way to handle numbers is with the 'struct' module
# Data to write
my_int = 255
my_float = 3.14159
# --- Method 1: Manual Conversion (Less common, but good to understand) ---
with open('numbers_manual.bin', 'wb') as f:
    # Convert integer to 2 bytes, big-endian
    int_bytes = my_int.to_bytes(2, 'big')
    f.write(int_bytes)
    # Convert float to 8 bytes, using IEEE 754 standard
    # This is complex and error-prone, which is why struct is better.
    # We'll use struct for the float part.
    float_bytes = struct.pack('!d', my_float) # '!' for network (big-endian), 'd' for double
    f.write(float_bytes)
print("File 'numbers_manual.bin' created with manual conversion.")
# --- Method 2: Using the `struct` Module (Highly Recommended) ---
# The struct module provides a more powerful and reliable way to pack
# data into bytes and unpack it back.
# Format string: '!d' means:
# ! - network byte order (big-endian)
# d - double-precision float (8 bytes)
# Let's also add an integer 'i' (4 bytes)
format_string = '!id' # One integer, one double
# Pack the data into a bytes object
packed_data = struct.pack(format_string, my_int, my_float)
with open('numbers_struct.bin', 'wb') as f:
    f.write(packed_data)
print("File 'numbers_struct.bin' created using the struct module.")
# --- Verification by reading back with struct ---
with open('numbers_struct.bin', 'rb') as f:
    # Unpack the data in the same order and format
    # The number of bytes read is determined by the format string
    read_int, read_float = struct.unpack('!id', f.read())
print(f"\nData read from 'numbers_struct.bin':")
print(f"Integer: {read_int}")
print(f"Float: {read_float}")

Example 3: Appending to a Binary File

If you want to add more data to the end of an existing binary file without overwriting it, use the 'ab' (append binary) mode.

Python如何写入二进制文件?-图3
(图片来源网络,侵删)
# Let's append another integer and float to our existing file
data_to_append = 12345
another_float = 2.71828
# Open the file in append binary mode ('ab')
with open('numbers_struct.bin', 'ab') as f:
    # Pack the new data and append it
    packed_append_data = struct.pack('!id', data_to_append, another_float)
    f.write(packed_append_data)
print("\nAppended new data to 'numbers_struct.bin'.")
# --- Verification ---
with open('numbers_struct.bin', 'rb') as f:
    # The file now contains 2 integers and 2 floats
    read_int1, read_float1, read_int2, read_float2 = struct.unpack('!idd', f.read())
print(f"\nFinal content of 'numbers_struct.bin':")
print(f"Integer 1: {read_int1}")
print(f"Float 1: {read_float1}")
print(f"Integer 2: {read_int2}")
print(f"Float 2: {read_float2}")

Key Takeaways and Best Practices

  1. Use 'wb' for creating/overwriting and 'ab' for appending.
  2. Always use the with open(...) as f: syntax. It ensures your file is automatically closed, even if errors occur.
  3. Write Bytes, Not Strings. If you have text, use .encode() to convert it to a bytes object before writing.
  4. Use the struct Module for Numbers. It's the standard, reliable way to pack and unpack C-style data structures (like integers and floats) into and from bytes. It handles byte order and size for you.
  5. Be Mindful of Byte Order. When using struct, for network byte order (big-endian) is a good default for cross-platform compatibility. If you are only reading/writing on the same machine, you can use < for little-endian or > for big-endian.
分享:
扫描分享到社交APP
上一篇
下一篇