Reputation: 151
I have a table of data in a txt file. I bring it into Python with:
a1_file=open(file_path,'r')
then I go to the second line to skip the headers:
a1_file.readline()
line_string=a1_file.readline()
Being a comma separated function I want to obtain a list where the position of the first 5 commas is stored. To this purspose I am trying to use this function:
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
I call the function with:
commas_in_line(line_string)
The code reports this error:
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()
with
>>> line_string
'30/04/2020,30,4,2020,122,0,Afghanistan,AF,AFG,37172386,Asia\n'
I tried substituting in the function:
commas=commas.append(k)
with:
commas=commas+[k]
and it works, but how can I use the append
method? Why does it fail?
Upvotes: 0
Views: 553
Reputation: 577
Essentially .append()
does not return the new array. .append()
is sort of like an inplace function, where the value is appended into the array. So you do not have to return anything. When you say commas=commas.append(k)
, a new entity is returned, which is NoneType. Please just leave it as commas.append(k)
Upvotes: 1
Reputation: 18
You add values to a python list with:
commas.append(k)
You use the =
operator to define a list, not to alter one. For instance, for
commas = ['a', 'b', 'c']
commas.append('d')
commas
will now be (a, b, c, d).
There is more about python lists here https://www.w3schools.com/python/python_lists.asp
Upvotes: 0