【问题标题】:How may I write a dictionary to a text file line by line format, replacing original text如何将字典逐行格式写入文本文件,替换原始文本
【发布时间】:2020-08-27 17:37:41
【问题描述】:

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

以下是我想将原始文本文件替换为的字典:

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

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

【问题讨论】:

    标签: python python-3.x file dictionary


    【解决方案1】:

    您不能只转储字典,因为就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)
    
    

    注意: 我没有测试过这些。

    【讨论】:

      【解决方案2】:

      在您的 write 语句中,您可以简单地这样做:

      f.write('\n'.join(car + ''.join(cars[car]) for car in cars))

      【讨论】:

        【解决方案3】:

        首先使用分隔符'\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')
        

        【讨论】:

          【解决方案4】:

          根据您的调试错误,您应该只像这样将 dict 转换为 str

          with open('cars.txt', 'w') as f:      
          f.write(str(cars)) 
          f.close()
          

          【讨论】:

            【解决方案5】:

            这里有多个问题:

            • 错误的意思是——你不能将dict 写入文件。
              • 要解决这个问题,只需将dict 转换为str,如下所示:dict_as_str = str(dict),然后是f.write(dict_as_str)
            • 一旦你解决了这个问题,看看你有什么:你可能看不到你想要的。这是因为f.write 转换它的方式与print 相同,所以如果你运行print(dict_as_str),它基本上看起来就像一个字典。
              • 要解决这个问题,您必须执行不止一行代码。我不会给你代码,你需要自己去尝试。如果您尝试过,但无法正常工作,那么您可以发布另一个问题。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2015-03-11
              • 2016-08-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-12-30
              • 1970-01-01
              • 2023-04-10
              相关资源
              最近更新 更多