[英]How to write a list to a text file exactly as it appears in python?
我希望能够将列表写到文本文件中,就像我只是将其在控制台中打印出来(带有括号和所有内容)时那样。 原因是,我以后需要使用该列表,并且该列表必须像打印时一样正常显示。
我已经尝试过使用csv模块,但是我无法按照自己的意愿格式化它。
有什么建议么?
尝试使用repr
。 repr“返回对象的规范字符串表示形式”,因此它应为您提供在交互式提示下检查内容时所打印的相同字符串。
file.write(repr(my_list))
如果您正在寻找更通用的解决方案,则可能要使用json:
import json
my_list = ['hello','world']
print json.dumps(my_list, indent=4, sort_keys=True, separators=(',', ': '))
输出为:
[
"hello",
"world"
]
它不仅对列表有用,而且:
my_dict = {
'hello':1,
'world':2
}
my_dict['my_list'] = my_list
print json.dumps(my_dict, indent=4, sort_keys=True, separators=(',', ': '))
输出为:
{
"hello": 1,
"my_list": [
"hello",
"world"
],
"world": 2
}
而且不错的部分是您可以使用“ json.loads”将字符串更改回原始值。 这是一个示例,您可以将字符串保存到文件中,并在以后阅读以重新创建字典:
with open(r'c:\my_dict.json', 'w') as f:
f.write(json.dumps(my_dict, indent=4, sort_keys=True, separators=(',', ': ')))
with open(r'c:\my_dict.json', 'r') as f:
data = f.read()
my_loaded_dict = json.loads(data)
print my_loaded_dict['my_list']
print my_loaded_dict.keys()
输出为(请注意,字符串现在是unicode):
[u'hello', u'world']
[u'world', u'my_list', u'hello']
您可以创建一个小的辅助函数来创建列表的字符串表示形式
def listify(l):
return '[{}]'.format(', '.join(map(str,l)))
>>> l = [1,2,3,4,5]
>>> listify(l)
'[1, 2, 3, 4, 5]'
在write
之前使用str:
>>> a = [1,2,3,4]
>>> b = str(a)
>>> b
'[1, 2, 3, 4]'
>>> file_descriptor.write(b)
您可以使用str
方法来包装字符串
In [21]: l = [1,2,3]
In [22]: with open("file_test", 'a') as f:
....: f.write(str(l) + "\n")
....:
In [23]:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.