我是编程新手。 我目前拥有的字典如下,我想将其写入一个文本文件(以行分隔),以替换文本文件中的原始内容。我已经更改了一些值并添加了新的键,我想知道如何去做
下面是我想用以下内容替换原始文本文件的词典:
cars={'Honda\n':['10/11/2020\n','red\n','firm and sturdy\n'
'breaks down occasionally\n'],'Toyota\n':['20/12/2005\n','indigo\n'
'big and spacious\n', 'fuel saving\n'],'Maserati\n':['10/10/2009\n','silver\n','fast and furious\n','expensive to maintain\n'],'Hyundai\n':['20/10/2000\n','gold\n','solid and reliable\n','slow acceleration\n']
原始文件:
Honda
10/11/2010
blue
strong and sturdy
breaks down occasionally
Toyota
20/15/2005
indigo
big and spacious
Maserati
10/10/2009
silver
fast and furious
expensive to maintain
accident prone
所需文件:
Honda
10/11/2020
red
firm and sturdy
breaks down occasionally
Toyota
20/12/2005
indigo
big and spacious
fuel-saving
Maserati
10/10/2009
silver
fast and furious
expensive to maintain
Hyundai
20/10/2000
gold
solid and reliable
slow acceleration
以下是我所做的:
with open('cars.txt', 'w') as f:
f.write(str(cars))
f.close()
但它只打印字典,而不是所需的文件。我能知道怎么做吗
首先使用分隔符
'\n\n'
拆分原始文件数据。然后使用字典访问新数据。然后将结果写入新文件您不能只转储字典,因为就
write
方法而言,您正在尝试转储内存位置您需要像这样检查每个字典键和条目。 您也不需要关闭文件,因为当您离开
with open
循环时,它将自行关闭注意: 我没有测试过这些
在书面声明中,您可以简单地执行以下操作:
f.write('\n'.join(car + ''.join(cars[car]) for car in cars))
相关问题 更多 >
编程相关推荐