I have a list of lists like the one below:
alist = [['Hi', 500], ['Bye', 500.0, 100, 900, 600], ['Great', 456, 700.0, 600], ["Yay", 200, 350.0], ["Ok", 200, 300, 400.0]]
I want to write this list to a .txt file in such a way that the textfile contents look something like this, with the first string written with a space after it, and the rest of the values separated by commas:
Desired output:
Hi 500
Bye 500.0,100,900,600
Great 246,700.0,600
Yay 200,350.0
Ok 200,300,400.0
This is what I’ve been trying out so far:
txtfile = open("filename.txt", "w")
for i in alist:
txtfile.write(i[0] + " ")
j = 1
while j < len(i):
txtfile.write([i][j] + ",")
txtfile.write("\n")
However, I just keep getting the IndexError("List Index out of range")
error.
Is there any way to solve this without importing any modules?
Thanks in advance 🙂
>Solution :
Other method.
alist = [['Hi', 500], ['Bye', 500.0, 100, 900, 600], ['Great', 456, 700.0, 600], ["Yay", 200, 350.0], ["Ok", 200, 300, 400.0]]
fn = "filename.txt"
mode = "w"
with open(fn, mode) as h: # file handle is auto-close
for v in alist:
h.write(v[0] + " ")
j = 1
while j < len(v):
if len(v) - 1 == j:
h.write(str(v[j])) # don't write a comma if this is the last item in the list
else:
h.write(str(v[j]) + ",")
j += 1 # increment j to visit each item in the list
h.write("\n")
Output
Hi 500
Bye 500.0,100,900,600
Great 456,700.0,600
Yay 200,350.0
Ok 200,300,400.0