gpt4 book ai didi

python - file.readines() 之后的 split() 出错

转载 作者:太空宇宙 更新时间:2023-11-04 10:45:59 25 4
gpt4 key购买 nike

我正在尝试通过使用 readlines() 进行阅读来使用 split()。我的部分代码如下:

with contextlib.nested(open("inpfile","r"), open("numberAmpdus", "w")) as (inf, ouf):
line = inf.readlines()
ampdu = line.split()

这不是使用 readlines() 读取行后应用拆分的方法吗?运行程序时,出现错误:

AttributeError: 'list' object has no attribute 'split'  

我应该在哪里更改我的代码?我使用的是python2.6。

最佳答案

file.readlines() 返回所有行的列表,列表没有任何 split 方法,这就是您收到该错误的原因。

lines = inf.readlines()

如果您尝试将 str.split 应用于 lines 的每个项目,那么您必须遍历此列表并应用 str.split 逐一添加到每一项。

ampdu = [x.split() for x in lines] # Applies `str.split` to each item of lines.
# This create a new list, a list of lists
# as `str.split` returns a list itself.

或:

for line in lines:
ampdu = line.split()
#now do something with `ampdu`

关于python - file.readines() 之后的 split() 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17285273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com