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

Python中os.open报TypeError:'str'无法转为整数的原因

解决文件读取时的TypeError: 'str' object cannot be interpreted as an integer

你遇到的错误根源是用错了函数:os.open() 是Python封装的底层系统级文件打开接口,它的第二个参数要求传入整数类型的权限标志(比如os.O_RDONLY表示只读),而不是像普通文件操作那样传字符串模式('r')。你把'r'这个字符串传给它,Python无法将字符串解析成整数,所以抛出了这个错误。

普通文件读取应该用Python内置的open()函数,这是面向开发者的高层接口,支持用字符串指定打开模式:

# 不需要导入os,因为用不到os.open
my_file = open('C:/Users/USER/Documents/20 Programming/Code institute 5 day coding challenge.txt', 'r')
my_file.close()

更推荐使用上下文管理器(with语句),它会自动帮你关闭文件,避免资源泄漏:

with open('C:/Users/USER/Documents/20 Programming/Code institute 5 day coding challenge.txt', 'r') as my_file:
    # 读取文件内容
    content = my_file.read()
    # 在这里编写去除多余换行的逻辑,例如:
    # processed_content = ' '.join(line.strip() for line in content.splitlines() if line.strip())

至于你替换成open()后遇到的文件未找到错误,属于路径校验问题,按照你的说明自行排查即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 00:38:35