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