python - Python:尝试使用我打开的文件的内容时出现 TypeError
问题描述
我真的是 python 或一般编程的新手,在过去的几个小时里我遇到了这个问题,我显然很糟糕地弄清楚出了什么问题。
def read_file(input_filename):
file_list = []
with open(input_filename, 'r') as open_file:
for x in range(len(open_file)):
print(open_file[x] + " [" + str(x) + "]")
if (x % 2) == 0:
thisTuple = (open_file[x], open_file[x + 1])
file_list.append(thisTuple)
我希望我能给予比感谢更多的帮助作为回报,但如果有人能给我任何关于我可能做错了什么的指示,那真的意义重大。
谢谢!
解决方案
您收到错误的原因是由于以下语句:
for x in range(len(open_file)):
open_file
没有实现__len__
Python 魔术函数。它也不是可下标的对象(如字符串)。它是一个TextIOWrapper
. 如果要将数据作为字符串获取,则需要调用open_file.read()
:
data= open_file.read()
for x in range(len(data)):
print(data[x] + " [" + str(x) + "]")
if (x % 2) == 0:
thisTuple = (data[x], data[x + 1])
file_list.append(thisTuple)
推荐阅读
- vue.js - 如何在 Vue.js 中使用不同的端口和相同的路径设置多个代理
- ios - 下载地址失败
- ios - 如何在复制的 ios 项目中更改 firestore 数据库?
- java - asynctask 在带有 api 24 的模拟器中工作,而不是在带有 api 28 的真实设备中工作
- c++ - GStreamer 管道在 gst_set_element_state 之后挂起
- java - 当 JDBC 依赖项包含在 Maven 中时,SQLite 的 java.lang.ClassNotFoundException (NetBeans 12.3)
- html - Web 视图和移动端看起来不同
- angular - Angular 12(节点:3224)UnhandledPromiseRejectionWarning:错误:无效映射:
- python - 尝试安装看门狗
- lua - roblox studio 中的 Inf 时间停止故障(ServerScriptService.TheWorldServer.TS:35:尝试使用“名称”索引 nil)