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

如何仅通过file://协议打印文本文件中的数据?

解决urllib读取本地文件输出对象而非内容的问题

urllib.request.urlopen()返回的是addinfourl对象,直接打印只会输出对象的元数据信息。要获取文件内容,需要调用对象的read()方法读取字节流,再解码为字符串。

修改后的代码示例:

import urllib.request

# 使用with语句自动关闭资源
with urllib.request.urlopen("file:///D:/Learnign/pro/Code%20Editor/d.txt") as data:
    # 根据文件实际编码调整解码格式,比如utf-8、gbk
    file_content = data.read().decode('utf-8')
    print(file_content)

如果不使用with语句,记得手动关闭资源:

import urllib.request

data = urllib.request.urlopen("file:///D:/Learnign/pro/Code%20Editor/d.txt")
file_content = data.read().decode('utf-8')
print(file_content)
data.close()

注意:如果文件是中文编码,可能需要将decode('utf-8')替换为decode('gbk'),避免出现乱码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 09:06:23