Python 将列表保存到 .txt 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33686747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save a list to a .txt file
提问by Luis Ramon Ramirez Rodriguez
Is there a function in python that allows us to save a list in a txt file and keep its format?
python中是否有一个函数可以让我们将列表保存在txt文件中并保持其格式?
If I have the list:
如果我有清单:
values = ['1','2','3']
can I save it to a file that contains:
我可以将其保存到包含以下内容的文件中吗?
'['1','2','3']'
So far I print parts of the list in the terminal and copy those in to a txt file.
到目前为止,我在终端中打印了部分列表并将它们复制到 txt 文件中。
采纳答案by Mangu Singh Rajpurohit
Try this, if it helps you
试试这个,如果它对你有帮助
values = ['1', '2', '3']
with open("file.txt", "w") as output:
output.write(str(values))
回答by Андрей Белоусов
If you have more then 1 dimension array
如果你有超过一维数组
with open("file.txt", 'w') as output:
for row in values:
output.write(str(row) + '\n')
回答by shantanu pathak
You can use inbuilt library pickle
您可以使用内置库泡菜
This library allows you to save any object in python to a file
这个库允许你将python中的任何对象保存到一个文件中
This library will maintain the format as well
该库也将保持格式
import pickle
with open('/content/list_1.txt', 'wb') as fp:
pickle.dump(list_1, fp)
you can also read the list back as an object using same library
您还可以使用相同的库将列表作为对象读回
with open ('/content/list_1.txt', 'rb') as fp:
list_1 = pickle.load(fp)
reference : Writing a list to a file with Python