Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to write a 'list of lists' to a .txt file in a certain format

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading