简体   繁体   中英

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.

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
with open('file.txt', 'w') as f:
    for lst in list_of_list:
        print(*lst, file=f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM