You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何写入字节到文件并读取为文本?能否用一个with实现?

Can I use one with statement to write bytes and read text from a file?

Absolutely! You can combine both operations into a single with statement, but you need to use the correct file mode and adjust the file pointer position after writing. Let's break this down:

First, let's clarify the mode strings:

  • wb: Write-only binary mode — truncates the file (overwrites existing content) and writes raw byte data. This is what you used in your first with block.
  • r: Read-only text mode — reads the file content as a string, using your system's default text encoding (usually UTF-8).
  • There is no wbr mode in Python — that's not a valid mode string, so avoid using it.

How to do it in one with statement

The key is to use w+b mode, which allows both writing binary data and reading binary data. After writing the bytes, you need to move the file pointer back to the start of the file before reading, otherwise you'll read from the end (and get an empty string). Then you can decode the bytes to text using the appropriate encoding.

Here's the example code:

myBytesVar = b'line1\nline2'
with open('myFile.txt', 'w+b') as f:
    # Write the byte data
    f.write(myBytesVar)
    # Move the file pointer back to the start
    f.seek(0)
    # Read the bytes and decode to text
    myVar = f.read().decode('utf-8')

print(myVar)

This will output:

line1
line2

Alternative: Open the file twice in one with statement

If you prefer to keep the write and read operations separate (using wb and r modes respectively), you can open two file handles in the same with statement. The with statement ensures the write handle is closed before the read operation starts, so you'll get the updated content:

myBytesVar = b'line1\nline2'
with open('myFile.txt', 'wb') as fw, open('myFile.txt', 'r') as fr:
    fw.write(myBytesVar)
    myVar = fr.read()

print(myVar)

This works too, but the first approach (using w+b) is more efficient since it only opens the file once.

Important notes:

  • When decoding bytes to text, always specify the encoding explicitly (like utf-8) instead of relying on the default, to avoid unexpected behavior across different systems.
  • If you're working with non-UTF-8 encoded text, adjust the decode() argument to match the correct encoding (e.g., latin-1).

内容的提问来源于stack exchange,提问作者Hrvoje T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:48:01