Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

ENH: Ensure lib._format_impl.read_array handles file reading errors. #28330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions 8 numpy/lib/_format_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,14 @@ def read_array(fp, allow_pickle=False, pickle_kwargs=None, *,
data = _read_bytes(fp, read_size, "array data")
array[i:i + read_count] = numpy.frombuffer(data, dtype=dtype,
count=read_count)

if array.size != count:
raise ValueError(
"Failed to read all data for array. "
f"Expected {shape} = {count} elements, "
f"could only read {array.size} elements. "
"(file seems not fully written?)"
)

if fortran_order:
array.shape = shape[::-1]
Expand Down
25 changes: 24 additions & 1 deletion 25 numpy/lib/tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,6 @@ def roundtrip_truncated(arr):
arr2 = format.read_array(f2)
return arr2


def assert_equal_(o1, o2):
assert_(o1 == o2)

Expand All @@ -451,6 +450,30 @@ def test_roundtrip_truncated():
if arr.dtype != object:
assert_raises(ValueError, roundtrip_truncated, arr)

def test_file_truncated(tmp_path):
path = tmp_path / "a.npy"
for arr in basic_arrays:
if arr.dtype != object:
with open(path, 'wb') as f:
format.write_array(f, arr)
#truncate the file by one byte
with open(path, 'rb+') as f:
f.seek(-1, os.SEEK_END)
f.truncate()
with open(path, 'rb') as f:
with pytest.raises(
ValueError,
match = (
r"EOF: reading array header, "
r"expected (\d+) bytes got (\d+)"
) if arr.size == 0 else (
r"Failed to read all data for array\. "
r"Expected \(.*?\) = (\d+) elements, "
r"could only read (\d+) elements\. "
r"\(file seems not fully written\?\)"
)
):
_ = format.read_array(f)

def test_long_str():
# check items larger than internal buffer size, gh-4027
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.