0

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 :)

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

Hi, in the output, I don't want a comma after the string, just a space. And in between the values, I only want a comma, no spaces. That is what is making me struggle with this problem
1

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

5 Comments

Hi, thank you for this. Is there a way to this without the map function.
@Pranav-sundaram you can use "."join([str(j) for j in i[1:]) to replace.
@Timus Sry, my bad. Forgot to remove it. :p
Oh, ok. Thank you so much.
Just add your (corrected) comment in the answer and then you have one :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.