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

如何解决Google Colab中访问上传文件的TypeError报错?

Fixing the 'dict_keys' Indexing Error in Google Colab for NumPy Files

Hey there! Let's sort out this error you're facing when trying to save your uploaded train_data.npy file in Google Colab.

What's causing the error?

In Python 3, the keys() method of a dictionary returns a dict_keys object—this is an iterable view of the dictionary's keys, but it doesn't support indexing (like using [0] to grab the first key). That's exactly why you're seeing TypeError: 'dict_keys' object does not support indexing.

On top of that, there's a second hidden issue: you're writing the file in text mode ('w'), but NumPy .npy files are binary files. Using text mode will corrupt the file, and you'll run into errors later when trying to load it with numpy.load().

Here's the corrected code

Let's fix both issues at once:

from google.colab import files
import numpy as np

# Upload your file
uploaded = files.upload()

# Print info about the uploaded file(s)
for filename in uploaded.keys():
    print(f'User uploaded file "{filename}" with length {len(uploaded[filename])} bytes')

# Get the first uploaded filename (correct, efficient way)
first_file = next(iter(uploaded.keys()))

# Save the file in BINARY write mode ('wb')
with open(first_file, 'wb') as f:
    f.write(uploaded[first_file])

# Optional: Verify the file loads correctly
train_data = np.load(first_file)
print(f"✅ Successfully loaded data! Shape: {train_data.shape}")

Key fixes explained:

  • next(iter(uploaded.keys())): This is the cleanest, most efficient way to get the first key from the uploaded dictionary. Instead of converting the keys to a list (which works but is unnecessary), we just iterate once and grab the first item.
  • 'wb' mode: The uploaded dictionary stores the file content as binary data, so we need to write it in binary mode to preserve the file's structure. Using 'w' would attempt to interpret the binary data as text, which breaks the NumPy file.

Bonus tip

If you're only uploading train_data.npy (and no other files), you can skip grabbing the first key entirely and just use the filename directly:

with open('train_data.npy', 'wb') as f:
    f.write(uploaded['train_data.npy'])

This makes your code more explicit if you know exactly which file you're working with.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:43:29