So I've been coding a 2d list that users can edit in python. At the end of this, I need to save the list into a txt file, then I get the error. This is the bit of code that's problematic:
tdlist = [["trash","laundry","dishes"],[1,2,3]]
items = numpy.array(tdlist)
savelist = open("list.txt", "w")
for row in items:
numpy.savetxt("list.txt", row)
savelist.close()
This is the wall of text error
Traceback (most recent call last):
File "/home/runner/ToDoList/venv/lib/python3.8/site-packages/numpy/lib/npyio.py", line 1450, in savetxt
v = format % tuple(row) newline
TypeError: must be real number, not numpy.str_
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 113, in <module>
numpy.savetxt("list.txt", row)
File "<__array_function__ internals>", line 180, in savetxt
File "/home/runner/ToDoList/venv/lib/python3.8/site-packages/numpy/lib/npyio.py", line 1452, in savetxt
raise TypeError("Mismatch between array dtype ('%s') and "
TypeError: Mismatch between array dtype ('<U21') and format specifier ('%.18e')
Any help is great, thanks!
CodePudding user response:
There are 2 problems. the format problem is only one of them. You mixed two ways of how to write content to a text file.
Either you open the file, write to it, and close it again. Could be done like this:
tdlist = [["trash", "laundry", "dishes"], [1, 2, 3]]
items = numpy.array(tdlist)
savelist = open("list.txt", "w")
for row in items:
savelist.write(", ".join(row) "\n") #needs to be a string
savelist.close()
or you just use numpy.savetxt
and write the whole items array in one step to a text file. Could be done like this:
tdlist = [["trash", "laundry", "dishes"], [1, 2, 3]]
items = numpy.array(tdlist)
numpy.savetxt("list.txt", items, fmt="%s") #like in the comments already mentioned, you need to specify a format here