gpt4 book ai didi

python - 解决 python 中的迭代 TypeError

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:57 24 4
gpt4 key购买 nike

我制作了一些文本文件,其格式如下:

['number', 'number', 'number']
number
number
number

但是,我的一些文件仅包含以下内容:

['number', 'number', 'number']

当我运行当前代码(如下所示)并遇到此类文件时,它会给出以下错误:

Traceback (most recent call last):
File "product_1digcon1.py", line 879, in <module>
punch_it()
File "product_1digcon1.py", line 875, in punch_it
last()
File "product_1digcon1.py", line 742, in last
finale()
File "product_1digcon1.py", line 775, in finale
for value, line in zip(values, fh):
TypeError: zip argument #1 must support iteration

我正在尝试修改我的代码,以便如果 zip 参数 #1 不支持迭代,则代码应移至下一个文件。这就是我到目前为止所写的内容。

def StDev():
for root, dirs, files in os.walk('/Users/Bashe/Desktop/12/'):
file = os.path.join(root, "Graph_StDev.txt")
file_name_out = os.path.join(root,"StDev.txt")
test = []
if os.path.exists(os.path.join(root,"Graph_StDev.txt")):
with open(file) as th, open(file_name_out,"w") as fh_out:
first_line = th.readline()
values = eval(first_line)
test.append(values)
test1 = str(test)
try:
float(test1)
if True:
for value, line in zip(values, th):
first_column = line.strip()
fh_out.write("%s\n" % (first_column))
except ValueError:
pass

任何帮助将不胜感激。

最佳答案

您可以使用 hasattr 函数检查对象是否支持迭代,该函数将检查魔术方法 iter。基本上,它将返回一个关于该对象是否支持迭代的 bool 值,因此如果不支持,您将不会迭代它。以下是代码示例,已修改为不对可迭代执行任何操作:

if hasattr(values,"__iter__"):                   #this checks if values is iterable
for value, line in zip(values, th):
first_column = line.strip()
fh_out.write("%s\n" % (first_column))
else:
pass #if you want to do anything if the object does not support iteration, do it here

这应该是你想要的,而且它比异常处理更干净、更简洁。

关于python - 解决 python 中的迭代 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20342322/

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