簡體   English   中英

如何將字典逐行寫入文本文件,替換原始文本

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM