如何将字典逐行格式写入文本文件,替换原始文本

我是编程新手。我目前有如下字典,我想将其写入文本文件(以行分隔)以替换文本文件中的原始内容。我更改了一些值并添加了新键,并且想知道如何去做。


下面是我想用其替换原始文本文件的字典:


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()

但它只打印字典而不是所需的文件。我可以知道该怎么做吗?


千万里不及你
浏览 188回答 5
5回答

Qyouu

您不能只转储字典,因为就该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)注意: 我还没有测试过这些。

喵喔喔

首先使用分隔符分割原始文件数据'\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')

慕尼黑8549860

根据您的调试错误,您应该只将dict转换为str像这样with open('cars.txt', 'w') as f:      f.write(str(cars)) f.close()

幕布斯6054654

在你的 write 语句中,你可以简单地这样做:f.write('\n'.join(car + ''.join(cars[car]) for car in cars))

蓝山帝景

这里有多个问题:该错误的意思就是它所说的——你不能将 a 写入dict文件。要解决这个问题,只需将 转换dict为 a str,如下所示:dict_as_str = str(dict),然后f.write(dict_as_str)一旦你解决了这个问题,看看你拥有什么:你可能不会看到你想要的。这是因为以f.write相同的方式转换它print,所以如果你运行print(dict_as_str),它基本上看起来像一个字典。要解决这个问题,您必须执行不止一行代码。我不会给你代码,你需要自己尝试弄清楚。如果您尝试但无法使其正常工作,那么您可以发布另一个问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python