numpy.genfromtxt与io.StringIO报错:TypeError: must be str or None, not bytes 求解
TypeError: must be str or None, not bytes with numpy.genfromtxt and io.StringIO Hey there! I’ve run into this exact issue before when working with Python 3, so let’s break down what’s happening and how to fix it quickly.
Why this error pops up
Python 3 draws a strict line between strings (str) and byte data (bytes), and io.StringIO is built only to handle string inputs. If you’re passing byte-formatted data (like stuff prefixed with b"...") into StringIO, or your data source outputs bytes instead of strings, numpy.genfromtxt will throw this error—it can’t read bytes from a StringIO buffer.
Two straightforward fixes
1. Swap io.StringIO for io.BytesIO (for byte data)
If your input is in bytes format (super common with raw data or file-like objects), use BytesIO instead—it’s made specifically for handling byte streams:
import numpy as np import io # Example byte data raw_data = b"1,2,3\n4,5,6\n7,8,9" # Use BytesIO to wrap byte inputs data_buffer = io.BytesIO(raw_data) # Now genfromtxt runs without errors result = np.genfromtxt(data_buffer, delimiter=",") print(result)
2. Decode byte data to strings first
If you’d rather stick with StringIO, just convert your byte data to a string using .decode() (use the correct encoding for your data—utf-8 works for most cases):
import numpy as np import io raw_data = b"1,2,3\n4,5,6\n7,8,9" # Turn bytes into a string data_str = raw_data.decode("utf-8") # Wrap the string with StringIO data_buffer = io.StringIO(data_str) result = np.genfromtxt(data_buffer, delimiter=",") print(result)
Either of these approaches will resolve the TypeError and let you use genfromtxt with in-memory data buffers smoothly.
内容的提问来源于stack exchange,提问作者Alex Rozhnov

