![](/img/trans.png)
[英]How do I write lines to a text file easily if I have a dictionary with the key of the line and contents being the text?
[英]How may I write a dictionary to a text file line by line format, replacing original text
我是编程新手。 我目前有如下字典,我想将其写入文本文件(以行分隔)以替换文本文件中的原始内容。 我更改了一些值并添加了新键,并且想知道如何去做。
下面是我想用以下内容替换原始文本文件的字典:
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()
但它只打印字典而不是所需的文件。 我能知道该怎么做吗?
您不能只转储字典,因为就write
方法而言,您正在尝试转储内存位置。
您需要像这样遍历每个字典键和项目。 您也不需要关闭文件,因为当您离开with open
环时,它会自行关闭。
with open('cars.txt', 'w') as f:
for car, vals in cars.items:
f.write(car)
for val in values:
f.write(val)
注意:我没有测试过任何这些。
在您的 write 语句中,您可以简单地执行以下操作:
f.write('\\n'.join(car + ''.join(cars[car]) for car in cars))
这里有多个问题:
dict
写入文件。
dict
转换为str
,如下所示: dict_as_str = str(dict)
,然后f.write(dict_as_str)
f.write
以与print
相同的方式转换它,所以如果你运行print(dict_as_str)
,它基本上看起来像一个字典。
首先使用分隔符'\\n\\n'
拆分原始文件数据。 然后使用字典访问新数据。 然后将结果写入新文件。
with open('cars.txt') as fp, open('new_cars.txt', 'w') as fw:
for car in fp.read().split('\n\n'):
car_name = car.split('\n', 1)[0] + '\n'
fw.write(car_name + ''.join(cars[car_name]) + '\n')
根据您的调试错误,您应该只将您的dict转换为str像这样
with open('cars.txt', 'w') as f:
f.write(str(cars))
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.