Writing a nested list into a text file?

Viewed 159

Hey guys python newbie here, if I were to run the below code:

test = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

with open('listfile.txt', 'w') as file:
    for item in test:
        for i in range(2):
            file.write("%s" % item)
            file.write("\n")

the text file looks like:

['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']

Any help on how I can make it look like this:

a    b    c
a    b    c
a    b    c
a    b    c

thanks in advance and please feel free to correct my coding.

3 Answers

You want to have tabs between each item rather than newlines. The second thing I change is I added file.write("\n") after the inner loop, in order to have a new line between each row. Finally I added file.close() to close the file.

test = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

with open('listfile.txt', 'w') as file:
    for item in test:
        for i in range(len(item)):
            file.write("%s" % item[i])
            file.write("\t") # having tab rather than "\n" for newline. 
        file.write("\n")
file.close()

Use ''.join()

with open('listfile.txt', 'w') as file:
    file.write('\n'.join('  '.join(item) for item in test))
with open('listfile.txt', 'w') as file:
    file.write('\n'.join(' '.join(map(str, lett)) for lett in test))

The code turns the list into a string with join, then separates the lines by joining them with a \n.

The output is this:

a b c
a b c
a b c
a b c

It looks like you wanted tabs, so you can join with \t instead of ' ':

test = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

with open('listfile.txt', 'w') as file:
    file.write('\n'.join('\t'.join(map(str, sl)) for sl in test))

Which outputs this:

a   b   c
a   b   c
a   b   c
a   b   c
Related