Mass17
Mass17

Reputation: 1605

Python: how to write a list of list to a text file?

I have a list of lists as follows:

list_of_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] 

I want to write down this to a file.txt in the following format.

1 2 3
4 5 6
7 8 9
10 11 12

Note that the commas & brackets are not there in the file.txt. I tried to flatten the list_of_list and wrote to file.txt but I got the following output:

1
2
3
etc.

Upvotes: 2

Views: 160

Answers (2)

Stefan Pochmann
Stefan Pochmann

Reputation: 28656

with open('file.txt', 'w') as f:
    for lst in list_of_list:
        print(*lst, file=f)

Upvotes: 5

Ed Ward
Ed Ward

Reputation: 2331

Try this:

lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

text = '\n'.join([' '.join([str(j) for j in i]) for i in lst])

with open("file.txt", "w") as file:
    file.write(text)

file.txt:

1 2 3
4 5 6
7 8 9
10 11 12

Upvotes: 5

Related Questions