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

List of lists write to file without brackets and commas

I have a list of lists e.g. testlist = [[1, 2, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] that I want to write them to file but replace commas with space and more specifically with a tab separator, \t which adds a big space between characters, so the final result inside the file would look like this:

1   2   3   4   5   6   7   8   9   10 #first list
11  12  13  14  15  16  17  18  19  20 #second list
...

I tried using replace() but I get error that I can’t use it with int chars. I have tried

for x in testlist:
    x.replace(",", "\t")

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

>Solution :

Hope this helps.

testlist = [[1, 2, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]]

with open("output.txt", "w") as f:
    for aList in testlist:
        myString = (''.join('{:<5}\t'*len(aList))).format(*aList,)
        print(myString)
        f.write(myString)

Output

1       2       4       5       6       7       8       9       10      
11      12      13      14      15      16      17      18      19      20 
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