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

如何在Google Colab中打开文本文件?上传后Python open函数调用失败

解决Colab中上传文件后无法用open打开的问题

嘿,我一眼就看出你代码里的问题啦~你用io.StringIO把上传的文件内容转成了内存里的类文件对象,但open()函数是用来读取本地文件路径字符串的,直接把StringIO对象传进去,它肯定找不到对应的文件,所以才会报错。

给你两种可行的解决方法,按需选择就行:

方法1:直接用StringIO对象读取内容

既然已经把文件内容加载到内存里了,直接调用StringIO的read()方法就行,不用再绕open了:

from google.colab import files
import io

uploaded = files.upload()
for fn in uploaded.keys():
    print('User uploaded file "{name}" with length {length} bytes'.format(
        name=fn, length=len(uploaded[fn])))

# 直接通过StringIO对象读取内容
data_file = io.StringIO(uploaded['fra.txt'].decode('utf-8'))
lines = data_file.read().split('\n')

方法2:先保存文件到Colab文件系统再打开

如果之后还需要反复用到这个文件,不如先把上传的内容写入Colab的本地文件系统,之后就可以像操作普通本地文件一样用open打开了:

from google.colab import files

uploaded = files.upload()
for fn in uploaded.keys():
    print('User uploaded file "{name}" with length {length} bytes'.format(
        name=fn, length=len(uploaded[fn])))
    # 把上传的二进制内容写入本地文件
    with open(fn, 'wb') as f:
        f.write(uploaded[fn])

# 现在可以正常用open打开文件路径了
with open('fra.txt', 'r', encoding='utf-8') as f:
    lines = f.read().split('\n')

简单总结:第一种适合临时处理一次性数据,第二种适合需要长期保留文件的场景~

内容的提问来源于stack exchange,提问作者Sriram Arvind Lakshmanakumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:40:01