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 :)
CodePudding user response:
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
CodePudding user response:
This is quick, easy and works without any imports:
str(alist).replace('],', '\n').replace('[', '').replace(']', '').replace("'", '')
Giving you:
Hi, 500
Bye, 500.0, 100, 900, 600
Great, 456, 700.0, 600
Yay, 200, 350.0
Ok, 200, 300, 400.0
Which you can write to disk as:
alist = str(alist).replace('],', '\n').replace('[', '').replace(']', '').replace("'", '')
with open('filename.txt', 'w') as f:
f.write(alist)
CodePudding user response:
maybe you can try this code:
to use list()
、map()
and str.join()
alist = [['Hi', 500], ['Bye', 500.0, 100, 900, 600], ['Great', 456, 700.0, 600], ["Yay", 200, 350.0], ["Ok", 200, 300, 400.0]]
t = open("a.txt", "w")
for i in alist:
t.writelines(i[0] " " ",".join(list(map(str, i[1:]))) "\n")
# if you want to do it without map()
# you can use list comprehension
# ","join([str(j) for j in i[1:])
and outputfile
Hi 500
Bye 500.0,100,900,600
Great 456,700.0,600
Yay 200,350.0
Ok 200,300,400.0