【发布时间】:2020-05-23 00:08:15
【问题描述】:
我有一个 txt 文件中的数据表。 我将它带入 Python:
a1_file=open(file_path,'r')
然后我转到第二行跳过标题:
a1_file.readline()
line_string=a1_file.readline()
作为逗号分隔的函数,我想获得一个列表,其中存储了前 5 个逗号的位置。为此,我正在尝试使用此功能:
def commas_in_line(table_row):
commas=[]
while len(commas) <5:
if len(commas)==0:
i=0
else:
i=commas[-1]+1
k=table_row.find(',',i)
commas=commas.append(k)
return commas
我调用函数:
commas_in_line(line_string)
代码报此错误:
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
commas_in_line(line_string)
File "C:/1WritingPrograms.py", line 11, in commas_in_line
while len(commas) <5:
TypeError: object of type 'NoneType' has no len()
与
>>> line_string
'30/04/2020,30,4,2020,122,0,Afghanistan,AF,AFG,37172386,Asia\n'
我尝试在函数中替换:
commas=commas.append(k)
与:
commas=commas+[k]
它有效,但我如何使用append 方法?为什么会失败?
【问题讨论】: