Home > OS >  List of lists write to file without brackets and commas
List of lists write to file without brackets and commas

Time:06-07

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

CodePudding user response:

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 

CodePudding user response:

This can be achieved without the aid of additional module imports as follows:

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 out_file:
    for e in testlist:
        print('\t'.join(map(str, e)), file=out_file)

CodePudding user response:

You can do it yourself, but he most pythonic way is to use csv library

here the example from official doc

import csv

with open('output.tsv', 'wt') as out_file:
    tsv = csv.writer(out_file, delimiter='\t')
    tsv.writerows(testlist)
  • Related