javanewbie javanewbie - 1 month ago 7
Python Question

'NoneType' TypeError when trying to append variable containing .write() to a file

I am attempting to save what I've written to a file in a variable and then append it to a wx.ListCtrl widget. However I get a 'NoneType' TypeError each time I try.

with open("birthday.txt", 'a') as database:
name = database.write(name_data + '\n')
mail = database.write(mail_data + '\n')

if int(month_data) < 10 and int(day_data) < 10:
date = database.write('0' + day_data + '/0' + month_data + '/' + year_data + '\n')

elif int(month_data) >= 10 and int(day_data) >= 10:
date = database.write(day_data + '/' + month_data + '/' + year_data + '\n')

elif int(month_data) < 10 and int(day_data) >= 10:
date = database.write(day_data + '/0' + month_data + '/' + year_data + '\n')

elif int(month_data) >= 10 and int(day_data) < 10:
date = database.write('0' + day_data + '/' + month_data + '/' + year_data + '\n')
database.write('\n')

index = self.list.InsertItem(sys.maxint, '1')
self.list.SetItem(index, 1, name) # Error message occurs here
self.list.SetItem(index, 2, mail)
self.list.SetItem(index, 3, date)


The error message:

TypeError: ListCtrl.SetItem(): arguments did not match any overloaded call:
overload 1: argument 1 has unexpected type 'long'
overload 2: argument 3 has unexpected type 'NoneType'

Answer

Writing to a file does not return the thing you wrote there in python. Here is your problem:

 name = database.write(name_data + '\n')
 mail = database.write(mail_data + '\n')
 ...
 date = database.write('0' + day_data + '/0' + month_data + '/' + year_data + '\n')

These write-operations do not return anything, so name, mail and date will always be None. That is why you get the error. Just remove the assignment:

database.write(name_data + '\n')

Instead you can just use the original variables in the SetItem-call, assuming you have defined them somewhere.

index = self.list.InsertItem(sys.maxint, '1')

By the way why would you pass this sys.maxint instead of, say, 0? I do not know much about wxpython. I'll make a guess and assume that with that the function returns list length as the index and will insert to the end, whereas 0 would insert to the start. Well, unimportant here probably.

Anyway, you can set the original data to the items:

self.list.SetItem(index, 1, name_data) 
self.list.SetItem(index, 2, mail_data)
self.list.SetItem(index, 3, date_data)

Ok you do not actually have the data_data like that, but that is another matter, I suggest you to look up how to use the datetime module to parse date data from strings. Or you can just do it the same way you did with the file write. Or at least a bit better would be to save the data to a variable there:

 data_data = '0' + day_data + '/0' + month_data + '/' + year_data + '\n'
 database.write(date_data)
Comments