Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何将列表写入文本文件?_Python_Python 3.x_List_Arraylist - Fatal编程技术网

Python:如何将列表写入文本文件?

Python:如何将列表写入文本文件?,python,python-3.x,list,arraylist,Python,Python 3.x,List,Arraylist,我的清单如下: list_of_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] 我想用下面的格式将其写入文件.txt 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 请注意,文件.txt中不存在逗号和括号。 我试图将列表的列表展平,并写入file.txt,但得到以下输出: 1 2 3 etc. 试试这个: lst = [[1, 2, 3], [4, 5, 6], [

我的清单如下:

list_of_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] 
我想用下面的格式将其写入
文件.txt

1 2 3
4 5 6
7 8 9
10 11 12
1 2 3
4 5 6
7 8 9
10 11 12
请注意,
文件.txt中不存在逗号和括号。
我试图将列表的
列表展平,并写入
file.txt
,但得到以下输出:

1
2
3
etc.
试试这个:

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


很好的回答,如果使用单个循环,并且不在
join
中创建两个不必要的列表,那么使用open('file.txt','w')作为f:for-internal\u-list中的list:f.write('.join(map(str,internal\u-list))+'\n')
@DeepSpace,你可以考虑把评论作为答案来回答。这能回答你的问题吗?
with open('file.txt', 'w') as f:
    for lst in list_of_list:
        print(*lst, file=f)